Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
662 views
in Technique[技术] by (71.8m points)

r - Error in file(file, "rt") : invalid 'description' argument in complete.cases program

I am writing an R function that reads a directory full of files and reports the number of completely observed cases in each data file. The function returns a data frame where the first column is the name of the file and the second column is the number of complete cases.

such as,

id nobs
1  108
2  345
...
etc

Here is the function I wrote:

complete <- function(directory, id = 1:332) {

  for(i in 1:332) {
    path<-paste(directory,"/",id,".csv",sep="")
    mydata<-read.csv(path)
    #nobs<-nrow(na.omit(mydata))
    nobs<-sum(complete.cases(mydata))
    i<-i+1
  }

  completedata<-c(id,nobs)
}

I execute the function:

complete("specdata",id=1:332)

but I'm getting this error:

Error in file(file, "rt") : invalid 'description' argument

I also tried the traceback() function to debug my code and it gives this output:

traceback()
# 4: file(file, "rt") at #6
# 3: read.table(file = file, header = header, sep = sep, quote = quote, 
#    dec = dec, fill = fill, comment.char = comment.char, ...) at #6
# 2: read.csv(path) at #6
# 1: complete("specdata", id = 1:332)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's hard to tell without a completely reproducible example, but I suspect your problem is this line:

path<-paste(directory,"/",id,".csv",sep="")

id here is a vector, so path becomes a vector of character strings, and when you call read.csv you're passing it all the paths at once instead of just one. Try changing the above line to

path<-paste(directory,"/",id[i],".csv",sep="")

and see if that works.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...