Eli*_*eth 2 url for-loop r 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
}
Run Code Online (Sandbox Code Playgroud)
就像@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)
Run Code Online (Sandbox Code Playgroud)
只是一个警告:所有数据框x必须具有相同的列才能执行此操作.如果其中一个条目x具有不同数量的列或不同名称的列,rbind则将失败.
在几个不同的包中存在更有效的行绑定功能(具有一些附加功能,例如列填充).看一下这些绑定行的解决方案:
plyr::rbind.fill()dplyr::bind_rows()data.table::rbindlist()