簡體   English   中英

將多個 CSV 加載到 R 中的對象

[英]Loading multiple CSVs to an object in R

我試圖將一堆 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

這行得通嗎?

編輯:為 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM