I had some data in a long format and I needed to convert it into a wide format. I have just achieved this objective but now I am struggling with how to export that file as a CSV.
Upon checking it looks like my wide data is a data frame with lists in it. Partial data is copied below:
dput()
dput(my_list)
structure(list(
id = c(428593707L, 430722191L, 430848712L, 431317885L, 432493351L, 435125247L),
`A1-ROL_SDRA_1_NA_score` = list(NULL, NULL, NULL, NULL, "2.1", NULL),
`A1-RW_SDRA_1_NA_score` = list(NULL, NULL, NULL, NULL, "2.1", NULL),
`A1-RW_SENS_1_NA_score` = list(NULL, NULL, "2.2", NULL, NULL, NULL),
`A2-MW_SBIO_1_NA_score` = list(NULL, NULL, NULL, NULL, NULL, NULL),
`A2-MW_SWS_1_NA_score` = list(NULL, "1.2", NULL, NULL, NULL, NULL),
`C1-AT_SADV_1_NA_score` = list(NULL, NULL, NULL, NULL, NULL, NULL),
`C1-AT_SBUS_2_NA_score` = list("3.1", NULL, NULL, NULL, NULL, NULL),
`C1-AT_SENS_1_NA_score` = list(NULL, NULL, "2.1", NULL, NULL, NULL),
`C1-AT_SENS_2_NA_score` = list(NULL, NULL, NULL, NULL, NULL, NULL),
row.names = c(NA, 6L), class = "data.frame")
Existing answers
I have tried the following solutions:
Solution 1
t <- as.data.frame(my_list)
write.csv(t, "wide_data.csv", row.names = F)
I get the following error message Error in utils::write.table(t, "wide_data.csv", row.names = F, : unimplemented type 'list' in 'EncodeElement'
Solution 2
I have also tried saving it as a list, based on this link https://www.rdocumentation.org/packages/erer/versions/3.0/topics/write.list
library('erer')
write.list(my_list, file = "wide_data.csv")
But I get this error Error in write.list(my_list, file = "wide_data.csv") : Need an 'list' object. And this is understandable as the my_list data is a dataframe of lists.
Solution 3
I tried the tibble() solution as well:
t <- my_list %>% as_tibble()
write.csv(t, "wide_data.csv", row.names = F)
Again, I get the error Error in utils::write.table(t, "wide_data.csv", row.names = F, : unimplemented type 'list' in 'EncodeElement'
Solution 4
I have tried column bind as well.
t = as.data.frame(do.call(cbind, my_list))
write.csv(t, "wide_data.csv", row.names = F)
Again, I get the error Error in utils::write.table(t, "wide_data.csv", row.names = F, : unimplemented type 'list' in 'EncodeElement'
Solution 5
I have tried row bind in the following way:
t = my_list %>% bind_rows()
write.csv(t, "wide_data.csv", row.names = F)
Again, I get the error Error in utils::write.table(t, "wide_data.csv", row.names = F, : unimplemented type 'list' in 'EncodeElement'
Can anyone advise how I can export this dataframe of lists as a CSV? I have been struggling for the past few days over this problem, any help would be greatly appreciated.
CodePudding user response:
The following solution seems to have worked. Thanks, @Ian Campbell
# Row bind
df = do.call(rbind, my_list)
# Take transpose
df2 = t(df)
write.csv(df2, "test.csv", row.names = F)
