我必须编写一个函数来读取一个完整的文件目录,并报告每个数据文件中完全观察到的情况的数量(每个可观察实例中没有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
之前读取该文件中的所有数据。这是错误的来源吗?或者是别的什么?请解释。谢谢!
看起来像你在做Coursera HW ... – Nate
在你的'for'循环中,你正在分配'data'(覆盖它)。 – steveb
第1周已经到期了吗? :) 祝你好运。我从这门课学到了很多东西。 –