循环读取一些 xlsx 文件
Reading some xlsx file in a loop
我有一个数据框,其中有一列在每一行中包含 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)}
问题是当它找不到文件时,显示错误并从 loop.But 出来我希望它转到下一行 instead.For 我写了一个 if像
这样的子句
if (file != 0)
next
但这对我没有帮助。有解决问题的想法吗?
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)
}
}
我有一个数据框,其中有一列在每一行中包含 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)}
问题是当它找不到文件时,显示错误并从 loop.But 出来我希望它转到下一行 instead.For 我写了一个 if像
这样的子句if (file != 0)
next
但这对我没有帮助。有解决问题的想法吗?
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)
}
}