gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:23:58 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com