I am new to R and I am practicing to write R functions. I have 100 cvs separate data files stored in my directory, and each is labeled by its id, e.g. "1" to "100. I like to write a function that reads some selected files into R, calculates the number of complete cases in each data file, and arrange the results into a data frame. Below is the function that I wrote. First I read all files in "dat". Then, using rbind function, I read the selected files I want into a data.frame. Lastly, I computed the number of complete cases using sum(complete.cases()). This seems straightforward but the function does not work. I suspect there is something wrong with the index but have not figured out why. Searched through various topics but could not find a useful answer. Many thanks!
`complete = function(directory,id) {
dat = list.files(directory, full.name=T)
dat.em = data.frame()
for (i in id) {
dat.ful= rbind(dat.em, read.csv(dat[i]))
obs = numeric()
obs[i] = sum(complete.cases(dat.ful[dat.ful$ID == i,]))
}
data.frame(ID = id, count = obs)
}
complete("envi",c(1,3,5)) `
get error and a warning message: Error in data.frame(ID = id, count = obs) : arguments imply differing number of rows: 3, 5