r - 将在线 .csv 文件合并到 R 中的数据框中

标签 r url for-loop download dataframe

我需要下载 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 
}

最佳答案

就像@RohitDas 所说的那样,连续添加数据帧效率很低,而且会很慢。只需下载每个 csv 文件作为列表中的条目,然后在收集列表中的所有数据后绑定(bind)所有行。

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 将失败。

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

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

关于r - 将在线 .csv 文件合并到 R 中的数据框中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34099634/

相关文章:

r - 从字符到日期/时间的转换返回 NA

java - 如何使用 Java 将 url(http 文件)上传到我的网络服务器?

c# - 一维数组中的条件语句

r - sqldf 和 POSIXct

r - 如何绕过嵌套的for循环?

asp.net - 如何正确地将 url 从自定义 asp.net 解决方案迁移到 Wordpress?

c++ - 动态更改嵌套的 for 循环顺序

latex - LaTeX 中的迭代

r - r 中的weighted.mean 命令工作得很奇怪

angular - 图标在 Angular 应用程序中不起作用