将多个CSV加载到R

时间:2016-10-15 12:08:25

标签: r csv merge data-analysis

我试图将一堆CSV文件放在一个文件夹中(一些在子目录中)并将它们全部加载到一个对象(每个CSV中的相同列)。我和rbind有一些运气,但无法完全自动化。

所以,下面的代码似乎很接近,但是我收到了一个错误。

 mytemp <- list.files(path="/PATH-TO-DIR/", recursive = TRUE, full.names = TRUE, pattern="*.csv")
    int_list = list
    for (i in mytemp.)
    {
      List1 <- read.csv(mytemp[i])[1:6]
      int_list <- rbind(int_list,List1)
    }
    int_list

我收到以下错误:

> int_list = list
> for (i in mytemp)
+ {
+ i
+ List1 <- read.csv(mytemp[i])[1:6]
+ int_list <- rbind(int_list,List1)
+ }
Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") : cannot open file 'NA': No such file or directory
> 

我做错了什么(多件事,我猜:):

我是R.的新手。我的大部分经验都是Java,因此对循环的迷恋:)。我也对非循环解决方案持开放态度。

谢谢!

-S

1 个答案:

答案 0 :(得分:1)

这有用吗?

编辑:为read.csv

添加了错误捕获器
 mytemp <- list.files(
    path="/PATH-TO-DIR/", 
    recursive = TRUE, 
    full.names = TRUE, 
    pattern="*.csv")
# check here if you're getting NA values somehow, which
# might cause that earlier error.
which(is.na(mytemp))
# if you get any answer other than integer(0), do this:
mytemp <- na.omit(mytemp)

myread <- function(fname, ...) {
    foo <- try(read.csv(fname, ...)[1:6])
    if(class(foo) == "try-error"){
        print(paste("problem reading:", fname))
    } else {
        return(foo)
    }
}

df_list <- lapply(mytemp, myread)
big_df <- do.call(rbind, df_list)