我必須編寫一個函數來讀取一個完整的文件目錄,並報告每個數據文件中完全觀察到的情況的數量(每個可觀察實例中沒有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周已經到期了嗎? :) 祝你好運。我從這門課學到了很多東西。 –