我有一个数据框,其中一列包含每行中的xlsx文件名,我想读取r中的每一行,然后添加一个列再保存它,所以为了这个目标,我写了一个循环,如: u = data.frame(V1 = c(“a”,“b”,“c”),stringsAsFactors = F)
for(i in 1:nrow(u) ){
#file name
dir = paste(u$V1[1], "_",i , ".xlsx" , sep="")
#reading the file: the problem is here
file<-read.xlsx(dir,1)
#making it as a dataframe
file.df<-as.data.frame(downloaded.file)
#Column which will added to the data
b <- u$V1[i]
#Adding a column
result<-cbind(b,file.df)
# File name
dir = paste("res" , i , ".txt" , sep="")
# Writing the result
write.table(result , file = dir , sep = "\t")
# Counting the list
print(i)}
问题在于,当它找不到文件时,显示错误并从循环中出来。但我希望它转到下一行。为此,我写了一个if子句,如
if (file != 0)
next
但它无法帮助我。有什么想法解决这个问题吗?
答案 0 :(得分:2)
u = data.frame(V1 = c("a", "b","c"),stringsAsFactors = F )
require(xlsx)
for(i in 1:nrow(u) ){
#file name
files <- list.files(pattern = "\\.xls") # gets both xls and xlsx
dir = paste(u$V1[1], "_",i , ".xlsx" , sep="")
#reading the file: the solution is here
if(dir %in% files){
file<-read.xlsx(dir,1)
#making it as a dataframe
file.df<-as.data.frame(downloaded.file)
#Column which will added to the data
b <- u$V1[i]
#Adding a column
result<-cbind(b,file.df)
# File name
dir = paste("res" , i , ".txt" , sep="")
# Writing the result
write.table(result , file = dir , sep = "\t")
# Counting the list
print(i)
}
}