2016-08-27 44 views
1

我必须编写一个函数来读取一个完整的文件目录,并报告每个数据文件中完全观察到的情况的数量(每个可观察实例中没有NA值)。该函数应该返回一个数据框,其中第一列是文件的名称,第二列是完整案例的编号。 请参阅下面的草稿,希望评论有帮助!如何在r中输出正确格式的数据帧?

complete <- function (directory, id = 1:332){ 
    nobs = numeric() #currently blank 
    # nobs is the number of complete cases in each file 
    data = data.frame() #currently blank dataframe 
    for (i in id){ 
    #get the right filepath 
    newread = read.csv(paste(directory,"/",formatC(i,width=3,flag="0"),".csv",sep="")) 
    my_na <- is.na(newread) #let my_na be the logic vector of true and false na values 
    nobs = sum(!my_na) #sum up all the not na values (1 is not na, 0 is na, due to inversion). 
    #this returns # of true values 
    #add on to the existing dataframe 
    data = c(data, i, nobs, row.names=i) 
    } 
    data # return the updated data frame for the specified id range 
} 

样品运行complete("specdata",1)的输出是

[[1]] 
[1] 1 

[[2]] 
[1] 3161 

$row.names 
[1] 1 

我不知道为什么它没有在常规数据帧格式显示。另外我很确定我的数字也不正确。 我正在假设在每个实例中,newread会在继续执行my_na之前读取该文件中的所有数据。这是错误的来源吗?或者是别的什么?请解释。谢谢!

+0

看起来像你在做Coursera HW ... – Nate

+1

在你的'for'循环中,你正在分配'data'(覆盖它)。 – steveb

+0

第1周已经到期了吗? :) 祝你好运。我从这门课学到了很多东西。 –

回答

2

您应该考虑将其他值添加到矢量的其他方法。该功能目前正在覆盖整个地方。你询问了id = 1时,当你给函数提供多个id时会更糟糕。它只会返回最后一个。这是为什么:

#Simple function that takes ids and adds 2 to them 
myFun <- function(id) { 

    nobs = c() 

    for(i in id) { 

    nobs = 2 + i 
    } 

    return(nobs) 
} 

myFun(c(2,3,4)) 
[1] 6 

我告诉它为每个id返回值加2,但它只给了我最后一个。我应该这样写:

myFun2 <- function(id) { 

    nobs = c() 

    for(i in 1:length(id)) { 

    nobs[i] <- 2 + id[i] 
    } 

    return(nobs) 
} 

myFun2(c(2,3,4)) 
[1] 4 5 6 

现在它给出正确的输出。有什么不同?首先nobs对象不会被覆盖,它被追加。请注意for循环标题中的子集括号和新计数器。

此外,建造对象不使用R.它最好的办法是内置了可事半功倍:

complete <- function(directory, id=1:332) { 
    nobs <- sapply(id, function(i) { 
    sum(complete.cases(read.csv(list.files(path=directory, full.names=TRUE)[i]))) }) 
    data.frame(id, nobs) 
} 

如果你想解决您的代码,你可以试试:

complete <- function (directory, id = 1:332){ 
    nobs = numeric(length(id)) #currently blank 
    # nobs is the number of complete cases in each file 
    for (i in 1:length(id)) { 
    #get the right filepath 
    newread = read.csv(paste(directory,"/",formatC(id[i] ,width=3,flag="0"),".csv",sep="")) 
    my_na <- is.na(newread) #let my_na be the logic vector of true and false na values 
    nobs[i] = sum(!my_na) #sum up all the not na values (1 is not na, 0 is na, due to inversion). 
    #this returns # of true values 
    } 
    data.frame(id, nobs) # return the updated data frame for the specified id range 
} 
0

由于我不知道你指的是什么数据,并且由于没有给定的样本,我能想出这个作为一个编辑给你的函数 -

complete <- function (directory, id = 1:332){ 
    data = data.frame() 
    for (i in id){ 
    newread = read.csv(paste(directory,"/",formatC(i,width=3,flag="0"),".csv",sep="")) 
    newread = newread[complete.cases(newread),] 
    nobs = nrow(newread) 
    data[nrow(data)+1,] = c(i,nobs) 
    } 
    names(data) <- c("Name","NotNA") 
    return(data) 
}