I'm trying to understand why part of my appended list is getting chopped off when exporting to excel. I can separate a dataframe by a grouping variable into separate lists:
data(iris)
split_tibble <- function(tibble, col = 'col') tibble %>% split(., .[, col])
spliris = split_tibble(iris,'Species') #creates list for each species having all variables
I have a separate list that looks like this:
mylist = list(cbind(col1 = c("val1","val2","val3","val4"),col2 = c("A","B","C","D")))
names(mylist) = "Table"
And I combine them into one list:
newlist = c(mylist,spliris) #looks correct so far
And I write out to an excel wb
#Create workbook with a sheet for each list element
library(openxlsx)
wb <- createWorkbook()
lapply(seq_along(newlist), function(i){
addWorksheet(wb=wb, sheetName = names(newlist[i]))
writeData(wb, sheet = i, newlist[[i]][-length(newlist[[i]])])
})
But when I save the workbook, the first sheet "Table" is incomplete and the two columns are just a single column.
Why does this happen? If I do not append the lists together and just write out the iris-lists it works perfectly:
#This works
wb <- createWorkbook()
lapply(seq_along(spliris), function(i){
addWorksheet(wb=wb, sheetName = names(spliris[i]))
writeData(wb, sheet = i, spliris[[i]][-length(spliris[[i]])])
})