0

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")
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
atreju
  • 965
  • 6
  • 15
  • 36
  • 1
    [Relevant](https://stackoverflow.com/questions/27208354/in-r-write-vectors-of-different-length-into-cvs-file). Maybe a dupe – Sotos Nov 01 '17 at 15:17
  • So what exactly does the desired output look like for this sample input. How do you want to line up columns when missing values are involved? – MrFlick Nov 01 '17 at 15:19
  • The first post worked for me. Thanks for pointing me in the right direction! – atreju Nov 01 '17 at 15:45

0 Answers0