R unlist changes names

后端 未结 2 774
余生分开走
余生分开走 2020-12-19 02:54

Given the following list:

l <- list(\"foo123\"=c(1:3), \"foo456\"=5, \"foo789\"=8)
print(l)
#  $foo123
#  [1] 1 2 3
#  
#  $foo456
#  [1] 5
#  
#  $foo789         


        
2条回答
  •  悲哀的现实
    2020-12-19 03:34

    This doesn't exactly answer your question, but an alternative that you can consider would be to go from a list to a "long" data.frame or data.table.

    This is easily achieved with stack in base R or melt from "reshape2" or "data.table".

    Example:

    stack(l)
    #   values    ind
    # 1      1 foo123
    # 2      2 foo123
    # 3      3 foo123
    # 4      5 foo456
    # 5      8 foo789
    
    library(data.table)
    melt(l)
    #   value     L1
    # 1     1 foo123
    # 2     2 foo123
    # 3     3 foo123
    # 4     5 foo456
    # 5     8 foo789
    

    Then, if you really wanted a named vector, you could always do:

    o <- data.table::melt(l)
    setNames(o$value, o$L1)
    # foo123 foo123 foo123 foo456 foo789 
    #      1      2      3      5      8 
    

提交回复
热议问题