2013-01-17 134 views
1

我使用下面的代碼中提取的完整的情況下,從文件數:返回一個數據幀

complete <- function(directory, id=1:332) { 
    sapply(id, fn, directory)} 


fn <- function(id, directory) { 
    zero <- sprintf("%03d", id) 
    name <- paste(directory,"/",zero,".csv",sep="") 
    frame <- read.csv(name) 
    ok <- complete.cases(frame) 
    return(c("nobs"=sum(ok),"id"=id)) } 

然後,例如:

complete("specdata",1:12) 

此代碼返回:

 [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] 
nobs 117 1041 243 474 402 228 442 192 275 148 443 96 
id  1 2 3 4 5 6 7 8 9 10 11 12 

但是,我希望它返回一個這樣的數據幀:

enter image description here

我不知道我在做什麼錯。謝謝!

+0

如果你把'瀏覽器()'你的函數調用中,你將能夠探索實時(你的)功能的內部運作。在SO上查看一些調試主題。 –

+0

這是對Coursera政策的公然違反 – EdwardGarson

回答

4

sapply在這裏返回matrix。你可以得到的形狀和鍵入要:

as.data.frame(t(complete("specdata",1:12))) 

或者把這個在complete功能,隨時待命,以sapplytmatrix行轉換爲列,as.data.frame將它強制轉換爲列。

0

您的代碼是確定的。爲了得到您想要的效果,請使用

t(sapply(id, fun, directory)) 

而不是sapply(id, fun, directory)

你的代碼應該是這樣的;

complete <- function(directory, id=1:332) { 
    t(sapply(id, fn, directory))} 
0
complete <- function(directory, id = 1:332) { 

as.data.frame(t(sapply(id, fn, directory))) 




} 

fn <- function(id, directory){ 
if(is.numeric(id)){               
id=id 
}else{ 
id = as.numeric(id) 
} 
fileName <- paste(paste(directory,'/',sep=''),paste(id,'.csv',sep=''),sep='') 
data <- read.csv(fileName) 
tows <- (complete.cases(data)) 
rowsNum <- nrow(data[tows,]) 
return(c("id"=as.numeric(id),"nobs"=rowsNum)) 

}