【问题标题】:Convert list to dataframe in R and add column with names of sub-lists将列表转换为 R 中的数据框并添加带有子列表名称的列
【发布时间】:2016-08-06 00:06:49
【问题描述】:

列表l 有三个字符串,分别命名为一、二和三。我想将l 转换为数据框,我需要一个附加列,其中包含n 中的名称。

l <- list(c("a", "b"), c("c", "d", "e"), c("e"))
n <- c("one", "two", "three")

我可以使用循环来做到这一点,但我确信有更有效的方法来做到这一点。

out <- NULL
for (i in 1:length(n)){
  step <- rep(n[i], length(l[[i]]))
  out <- c(out, step)}

df <- as.data.frame(unlist(l))
df$n <- out
df

#  unlist(l)     n
#1         a   one
#2         b   one
#3         c   two
#4         d   two
#5         e   two
#6         e three

【问题讨论】:

    标签: r list dataframe


    【解决方案1】:

    使用基础 R,您基本上可以分两行完成。

    l <- list(c("a", "b"), c("c", "d", "e"), c("e"))
    n <- c("one", "two", "three")
    
    #Create an appropriately sized vector of names
    nameVector <- unlist(mapply(function(x,y){ rep(y, length(x)) }, l, n))
    
    #Create the result
    resultDF <- cbind.data.frame(unlist(l), nameVector)
    
    
    > resultDF
      unlist(l) nameVector
    1         a        one
    2         b        one
    3         c        two
    4         d        two
    5         e        two
    6         e      three
    

    【讨论】:

      【解决方案2】:

      另一种选择是在将列表中每个元素的名称设置为向量后使用stack

      stack(setNames(l, n))
      
      #  values   ind
      #1      a   one
      #2      b   one
      #3      c   two
      #4      d   two
      #5      e   two
      #6      e three
      

      【讨论】:

        【解决方案3】:

        另一个类似的基本 R 选项:

        do.call(rbind, Map(f = expand.grid, l = l, n = n, stringsAsFactors = F))
        #   l     n
        # 1 a   one
        # 2 b   one
        # 3 c   two
        # 4 d   two
        # 5 e   two
        # 6 e three
        

        【讨论】:

          【解决方案4】:

          另一个选项是melt 来自reshape2

          library(reshape2)
          melt(setNames(l, n))
          #  value    L1
          #1     a   one
          #2     b   one
          #3     c   two
          #4     d   two
          #5     e   two
          #6     e three
          

          base R

          data.frame(value = unlist(l), key = rep(n, lengths(l)))
          #   value   key
          #1     a   one
          #2     b   one
          #3     c   two
          #4     d   two
          #5     e   two
          #6     e three
          

          【讨论】:

            猜你喜欢
            • 2019-06-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-11-14
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多