6
I’m trying to build a function that counts the number of complete cases in files. csv (data frames), ie the number of lines with values (and not "NA"). The function I wrote can read the file(s) specified in the function call and count the number of rows with complete cases, but I need to return this information as a data frame, with 2 columns, "id" for the file identification (they are all identified with numbers) and "Nobs" for the number of observations (the complete cases). In this function, my read loop cannot then store the count results in that data frame. The figure below has some examples of what the function should return.
That’s the job of:
completeF<-function(directory,id) {
#set file location
address<-paste(getwd(), directory, sep="/")
#Creates objects for later results keeping
Completev<-data.frame(matrix(0,1,ncol=2))
temp<-data.frame(matrix(0,1,ncol=2))
#colnames(Completev)<-c("id","Nobs")
#colnames(temp)<-c("id","Nobs")
#read files
files <- dir(directory)
for (i in id){
#read files
each.file<-read.csv(paste(address,files[i],sep="/"),h=TRUE)
#count complete cases: count number of lines with values for sulfate and nitrate
obs<-na.omit(each.file)
rowcount <- nrow(obs)
#keep results in temporary data frame, and then the final one
temp<-cbind(i,rowcount)
Completev<-rbind(Completev,temp)
}
colnames(Completev)<-c("id","Nobs")
return(Completev)
}
But what I get is
> completeF("specdata",1:5)
Error in match.names(clabs, names(xi)) :
names do not match previous names
Running Traceback, I understood that the error occurs here: Completev<-rbind(Completev,temp), with the rbind, but I don’t understand why! Even fixing the names of the columns before the "for" loop, it solves.
What could be wrong in the loop?
That worked, Anthony! Thank you!
– Leila
Hey, Leila, nice to help. Here in Stack Overflow you can indicate that a response is good or bad by voting on it (with the arrow up or the arrow down). If an answer solved your problem you can also accept it (green symbol of "correct" below the votes). With these signals you help other people who bump into similar problems.
– Anthony Accioly
Anthony, I tried to vote, but I have to have 15 reputation points... but I’ve already accepted your answer. :^)
– Leila
No problem Leila, thank you.
– Anthony Accioly