[英]How to loop over several lists to make dataframes in R?
I need to create a loop for converting several list into dataframe, and then write each dataframe as csv. 我需要创建一个循环,将多个列表转换为数据帧,然后将每个数据帧写为csv。 I mean, I want to (i) run a loop for unlist all my lists + convert them into data.frames, and (ii) write each list as CSV.
我的意思是,我想(i)运行循环以取消列出我的所有列表+将它们转换为data.frames,以及(ii)将每个列表写为CSV。
I ran the following scrip which works for one of my lists but I need to do the same for many of them. 我运行了以下脚本,该脚本适用于我的一个列表,但我需要对其中许多列表执行相同的操作。
Script to convert a nested list (eg, list1) in data frame, and write as CSV 用于在数据框中转换嵌套列表(例如,list1)的脚本,并写为CSV
data <- as.data.frame(t(do.call(rbind,unlist(list1,recursive = FALSE))))
write.csv(data,"list1.csv"))
Please note that "list1" is one of my list that I wrote as an example. 请注意,“list1”是我作为示例编写的列表之一。 I created an script (
done <- ls(pattern="list")
) to get a vector with the name of all my lists load in the R environment. 我创建了一个脚本(
done <- ls(pattern="list")
)来获取一个载体,其中包含我在R环境中加载的所有列表的名称。 So that, I should apply the step (i) and (ii) to all the names in the "done" vector. 因此,我应该将步骤(i)和(ii)应用于“完成”向量中的所有名称。 Was it clearer now?
现在更清楚了吗?
I would really appreciate if you can help me to create the loop? 如果你能帮我创建循环,我真的很感激?
for(i in 1:nrow(done){
list_name <- done[i]
data <- as.data.frame(t(do.call(rbind,unlist(noquote(list_name),recursive = FALSE))))
write.csv(data,paste0(list_name,".csv"))
}
fun <- function(x){
data <- as.data.frame(t(do.call(rbind,unlist(paste0("list",x),recursive = FALSE))))
write.csv(data,paste0("list",x,".csv"))
}
fun(1:n)
I believe this is the most efficient way. 我相信这是最有效的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.