【问题标题】:Combine online .csv files into data frame in R将在线 .csv 文件合并到 R 中的数据框中
【发布时间】:2015-12-05 00:16:02
【问题描述】:

我需要下载 300 多个在线可用的 .csv 文件,并将它们组合成 R 中的数据框。它们都具有相同的列名,但长度(行数)不同。

l<-c(1441,1447,1577)
s1<-"https://coraltraits.org/species/"
s2<-".csv"

for (i in l){   
    n<-paste(s1,i,s2, sep="") #creates download url for i
    x <- read.csv( curl(n) ) #reads download url for i
    #need to sucessively combine each of the 3 dataframes into one 
}

【问题讨论】:

  • read.csv 接受网址:tmp &lt;- do.call('rbind', tmp1 &lt;- Vectorize(read.csv, SIMPLIFY = FALSE)(paste0(s1, l, s2))) 其中tmp1 将包含您的数据框列表,tmp 将它们组合在一起

标签: r url for-loop download dataframe


【解决方案1】:

就像@RohitDas 说的,不断地追加一个数据框是非常低效的并且会很慢。只需将每个csv文件下载为列表中的条目,然后在收集列表中的所有数据后绑定所有行。

l <- c(1441,1447,1577)
s1 <- "https://coraltraits.org/species/"
s2 <- ".csv"

# Initialize a list
x <- list()

# Loop through l and download the table as an element in the list    
for(i in l) {   
    n <- paste(s1, i, s2, sep = "") # Creates download url for i
    # Download the table as the i'th entry in the list, x
    x[[i]] <- read.csv( curl(n) ) # reads download url for i
}

# Combine the list of data frames into one data frame
x <- do.call("rbind", x)

只是一个警告:x 中的所有数据框必须具有相同的列才能执行此操作。如果x 中的条目之一具有不同数量的列或不同名称的列,则rbind 将失败。

更高效的行绑定功能(带有一些额外功能,例如列填充)存在于几个不同的包中。看看其中一些用于绑定行的解决方案:

  • plyr::rbind.fill()
  • dplyr::bind_rows()
  • data.table::rbindlist()

【讨论】:

    【解决方案2】:

    如果它们具有相同的列,那么它只是附加行的问题。一个简单(但不是内存效率)的方法是在循环中使用 rbind

    l<-c(1441,1447,1577)
    s1<-"https://coraltraits.org/species/"
    s2<-".csv"
    
    data <- NULL
    for (i in l){   
        n<-paste(s1,i,s2, sep="") #creates download url for i
        x <- read.csv( curl(n) ) #reads download url for i
        #need to sucessively combine each of the 3 dataframes into one 
        data <- rbind(data,x)
    }
    

    一种更有效的方法是构建一个列表,然后在最后将它们组合成一个数据框,但我将把它留给你作为练习。

    【讨论】:

    • “但我会把它留给你作为练习。”哈哈。而是在你的答案中显示出来。
    • 感谢您的解决方案 Rohit。您的解决方案有效,但是正如您所说,它的内存效率有点低。我有 370 个在线 csv 文件,每个文件大约 30 x 200)要组合。所以可能需要考虑列表替代方案。
    猜你喜欢
    • 1970-01-01
    • 2019-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-14
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    相关资源
    最近更新 更多