In R write list with several elements to data.frame

后端 未结 4 356
自闭症患者
自闭症患者 2021-01-29 05:51

I have a named list whose each element is a character vector. I want to write this list into a single dataframe where I have two columns, one with the name of the character vect

相关标签:
4条回答
  • 2021-01-29 06:06

    Maybe

    data.frame(vecname = rep(names(ll), sapply(ll, length)), chars = unlist(ll))
    

    to have each element of each list component correspond to a row in the final dataframe.

    0 讨论(0)
  • 2021-01-29 06:07

    I'm wondering if stack provides the functions you need (using the example of Henrik)

    ll <- list(x1 = c("a", "b", "c"), x2 = c("d", "e"))
    stack(ll)
    #-------
      values ind
    1      a  x1
    2      b  x1
    3      c  x1
    4      d  x2
    5      e  x2
    
    0 讨论(0)
  • 2021-01-29 06:16
     NewList <- lapply(names(List), function(X) data.frame(Names=X, Characters=List[[X]]))
     do.call(rbind, NewList)
    
    0 讨论(0)
  • 2021-01-29 06:19

    A very straightforward way would be to use cbind(), like this:

    cbind(names(l),l)
    

    This will result in the following data frame, assuming that l = list(a="ax", b="bx"):

          l   
    a "a" "ax"
    b "b" "bx"
    

    Of course, you can rename the columns and rows by adjusting the values in colnames(l) and rownames(l). In this example, the string names are automatically also applied to the rownames of the resulting data frame, so, depending on what you'd like to do with your data,

    cbind(l)
    

    might suffice, resulting in

      l   
    a "ax"
    b "bx"
    

    Hope I could help.

    0 讨论(0)
提交回复
热议问题