英文:
Saving a list of dataframes into separate CSVs in R
问题
我有一个数据框列表:
group_eg <- data.frame(
CID = c(091, 091, 091, 091,
101, 101, 101,
102, 102, 102,
103, 103,
104, 104, 104),
PID_A = c(1091, 1091, 1091, 1091,
1101, 1101, 1101,
1102, 1102, 1102,
1103, 1103,
1104, 1104, 1104),
PID_B = c(2091, 2091, 2091, 2091,
2101, 2101, 2101,
2102, 2102, 2102,
2103, 2103,
2104, 2104, 2104),
text = c("eg1", "eg2", "eg3", "eg3",
"eg4","eg5", "eg6",
"eg7", "eg8","eg9",
"eg10", "eg11",
"eg12", "eg13", "eg14")
)
group_eg_split <- split(group_eg, paste0("output_", ceiling(rleid(group_eg$CID)/2)))
我尝试将列表中的每个数据框保存到单独的CSV文件中,并使用相应的名称。到目前为止,我有以下内容:
lapply(1:length(group_eg_split), function(i) write.csv(group_eg_split[[i]],
file = paste0(names(group_eg_split[i]), ".csv"),
row.names = FALSE))
但它返回一个NULL值。我应该如何修改它?
谢谢!
英文:
I have a list of dataframes:
group_eg <- data.frame(
CID = c(091, 091, 091, 091,
101, 101, 101,
102, 102, 102,
103, 103,
104, 104, 104),
PID_A = c(1091, 1091, 1091, 1091,
1101, 1101, 1101,
1102, 1102, 1102,
1103, 1103,
1104, 1104, 1104),
PID_B = c(2091, 2091, 2091, 2091,
2101, 2101, 2101,
2102, 2102, 2102,
2103, 2103,
2104, 2104, 2104),
text = c("eg1", "eg2", "eg3", "eg3",
"eg4","eg5", "eg6",
"eg7", "eg8","eg9",
"eg10", "eg11",
"eg12", "eg13", "eg14")
)
group_eg_split <- split(group_eg, paste0("output_", ceiling(rleid(group_eg$CID)/2)))
I am trying to save each dataframe in the list to a separate CSV file with its corresponding name. This is what I have so far:
lapply(1:length(group_eg_split), function(i) write.csv(group_eg_split[[i]],
file = paste0(names(group_eg_split[i]), ".csv"),
row.names = FALSE))
But it's returning a NULL value. How can I modify it?
Thank you!
答案1
得分: 0
Your code is correct, but the dataframes are exported in CSV, and it returns NULL
because your function write.csv()
returns NULL
. If you don't want it, you can update your code and return what you want (the exported dataframes or just a message).
lapply(1:length(group_eg_split),
function(i){
write.csv(
group_eg_split[[i]],
file = paste0(names(group_eg_split[i]), ".csv"),
row.names = FALSE)
return(group_eg_split[[i]])
}
)
如果你更喜欢返回消息而不是数据框,可以将 return(...)
替换为 return(print("导出成功。"))
。
英文:
Your code is correct <i>ie</i> the dataframes are exported in csv. And it returns NULL
because your function write.csv()
returns NULL
. If you don't wan't it, you can update your code and return what you want (the exported dataframes or just a message).
lapply(1:length(group_eg_split),
function(i){
write.csv(
group_eg_split[[i]],
file = paste0(names(group_eg_split[i]), ".csv"),
row.names = FALSE)
return(group_eg_split[[i]])
}
)
You can replace return(...)
by return(print("Export OK."))
if you prefer a message rather than the dataframes.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论