Home > Blockchain >  Convert Each Element in List to a Column in a Data Frame
Convert Each Element in List to a Column in a Data Frame

Time:12-31

Suppose I have the following list "d":

library(combinat)
d = permn(c("a", "b", "c"))

This looks as follows:

[[1]]
[1] "a" "b" "c"

[[2]]
[1] "a" "c" "b"

[[3]]
[1] "c" "a" "b"

[[4]]
[1] "c" "b" "a"

[[5]]
[1] "b" "c" "a"

[[6]]
[1] "b" "a" "c"

Is it possible to convert each element of this list into a column?

This is what I am trying to do:

desired_result = data.frame(col1 = c("a", "b", "c"), col2 = c("a", "c", "b"), col3 = c("c", "a", "b"), col4 = c("c", "b", "a"), col5 = c("b", "c", "a"), col6 = c("b", "a", "c"))

 col1 col2 col3 col4 col5 col6
1    a    a    c    c    b    b
2    b    c    a    b    c    a
3    c    b    b    a    a    c

Can someone please show me how to do this?

Thanks!

CodePudding user response:

Try matrix(unlist(d), ncol = length(d)) or, if you need a data frame, data.frame(matrix(unlist(d), ncol = length(d)) for any length of d

CodePudding user response:

We can use a matrix as intermediary step to finally convert to a data.frame, and specifying column names:

as.data.frame(matrix(unlist(d), ncol = 6)) |>
  setNames(paste0("col", 1:6))
  col1 col2 col3 col4 col5 col6
1    a    a    c    c    b    b
2    b    c    a    b    c    a
3    c    b    b    a    a    c
  • Related