2016-06-28 77 views
1

我有一個數據幀,其中包含每行中的xlsx文件名的列,我想讀取r中的每一行,然後添加一列到保存它,所以爲此目標我寫像一個循環: U = data.frame(V1 = C( 「A」, 「b」, 「C」),stringsAsFactors = F)在循環中讀取一些xlsx文件

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)} 

的問題是,當它不」 t找到一個文件,顯示一個錯誤並從循環中出來,但我希望它可以轉到下一行。爲此,我寫了一個if子句,如

if (file != 0) 
     next 

但它不能幫助我。任何想法解決這個問題?

+1

類似'file.exists(「點心」)''。 – lmo

回答

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) 
    } 
}