I have been struggling for some time to generate a specific output format using R, namely a tab-separated multi-list file, with each column representing one list and the first row containing the names of the individual lists.
I have saved the individual lists in a list object:
multi_list <- list(vector1=c(1,2,3),vector2=c(4,5),vector3=c(6,7,8,9),vector4=c(10))
My problem consists in the fact that the individual lists are of different lengths and thus cannot be concatenated as a data frame without adding NA
values to the shorter lists which doesn’t work for the required output format.
How can I write my multi-list to a tsv file with each vector as a separate column?
Edit:
I found a solution based on the answer to this question as suggested below. May not be the most elegant way but it works:
df <- data.frame(vector1 = rep(NA, max(sapply(multi_list, length))))
df[1:length(multi_list$vector1), 1] <- multi_list$vector1
df[1:length(multi_list$vector2), 2] <- multi_list$vector2
df[1:length(multi_list$vector3), 3] <- multi_list$vector3
df[1:length(multi_list$vector4), 4] <- multi_list$vector4
colnames(df) <- c("vector1", "vector2", "vector3", "vector4")
write.table(df, file = 'multi_list.tsv', row.names = FALSE, na = '', sep="\t")