在 R 中的不同 excel 工作表中追加不同列表的元素
append elements of differet lists in different excel sheets in R
我有一个这样的第一个列表:
[[First]]
y sum_1
1 2009 35
2 2010 30
3 2011 20
[[Second]]
y sum_1
1 2009 6
2 2010 21
3 2011 40
第二个列表:
[[First]]
y sum_2
1 2009 20
2 2010 30
3 2011 12
[[Second]]
y sum_2
1 2009 9
2 2010 24
3 2011 33
和其他列表。
我想将列表的每个元素导出到同一 excel 文件的不同 sheet。
我用这段代码做了这个:
wb <- createWorkbook()
Map(function(data, nameofsheet){
addWorksheet(wb, nameofsheet)
writeData(wb, nameofsheet, data)
}, listofdfs, names(listofdfs))
saveWorkbook(wb, file = "C:\Users\prova.xlsx", overwrite = TRUE)
但这适用于一个列表。我不知道如何将第二个列表的 'First' 元素 'append' 到 excel sheet 中第一个列表的 'First' 元素,然后'Second' 等等。
谢谢!
我们可以将dataframes列表绑定为一个,然后根据名称拆分它们并使用write.xlsx
。
library(openxlsx)
library(dplyr)
data <- bind_rows(list1, .id = 'id') %>%
bind_rows(bind_rows(list2, .id = 'id')) %>%
split(.$id)
write.xlsx(data, file = "data.xlsx")
数据
答案中的list1
、list2
是:
list1 <- list(First = structure(list(y = 2009:2011, sum_1 = c(35L, 30L,
20L)), class = "data.frame", row.names = c("1", "2", "3")),
Second = structure(list(y = 2009:2011, sum_1 = c(6L, 21L, 40L)),
class = "data.frame", row.names = c("1", "2", "3")))
list2 <- list(First = structure(list(y = 2009:2011, sum_2 = c(20L, 30L,
12L)), class = "data.frame", row.names = c("1", "2", "3")),
Second = structure(list(y = 2009:2011, sum_2 = c(9L, 24L, 33L)),
class = "data.frame", row.names = c("1", "2", "3")))
我有一个这样的第一个列表:
[[First]]
y sum_1
1 2009 35
2 2010 30
3 2011 20
[[Second]]
y sum_1
1 2009 6
2 2010 21
3 2011 40
第二个列表:
[[First]]
y sum_2
1 2009 20
2 2010 30
3 2011 12
[[Second]]
y sum_2
1 2009 9
2 2010 24
3 2011 33
和其他列表。
我想将列表的每个元素导出到同一 excel 文件的不同 sheet。 我用这段代码做了这个:
wb <- createWorkbook()
Map(function(data, nameofsheet){
addWorksheet(wb, nameofsheet)
writeData(wb, nameofsheet, data)
}, listofdfs, names(listofdfs))
saveWorkbook(wb, file = "C:\Users\prova.xlsx", overwrite = TRUE)
但这适用于一个列表。我不知道如何将第二个列表的 'First' 元素 'append' 到 excel sheet 中第一个列表的 'First' 元素,然后'Second' 等等。
谢谢!
我们可以将dataframes列表绑定为一个,然后根据名称拆分它们并使用write.xlsx
。
library(openxlsx)
library(dplyr)
data <- bind_rows(list1, .id = 'id') %>%
bind_rows(bind_rows(list2, .id = 'id')) %>%
split(.$id)
write.xlsx(data, file = "data.xlsx")
数据
答案中的list1
、list2
是:
list1 <- list(First = structure(list(y = 2009:2011, sum_1 = c(35L, 30L,
20L)), class = "data.frame", row.names = c("1", "2", "3")),
Second = structure(list(y = 2009:2011, sum_1 = c(6L, 21L, 40L)),
class = "data.frame", row.names = c("1", "2", "3")))
list2 <- list(First = structure(list(y = 2009:2011, sum_2 = c(20L, 30L,
12L)), class = "data.frame", row.names = c("1", "2", "3")),
Second = structure(list(y = 2009:2011, sum_2 = c(9L, 24L, 33L)),
class = "data.frame", row.names = c("1", "2", "3")))