【问题标题】:Flattening vector containing lists in R [duplicate]R中包含列表的展平向量[重复]
【发布时间】:2016-12-06 19:49:30
【问题描述】:

我正在尝试展平包含多个列表的向量。在保留与该列表关联的数据的同时,最好的方法是什么?我尝试使用 unlist ,但这给了我一个未连接到我的数据的列表。

## My data set looks something like this:
df <- data.frame(A = c(1,2,3),
                 B = c(3,5,4),
                 C = c(4,3,5),
                 D = c(7,9,2))
df$E <- list(c(5, 3, 2, 1), 5, c(5, 2, 1))
df
##  A B C D          E
## 1 1 3 4 7 5, 3, 2, 1
## 2 2 5 3 9          5
## 3 3 4 5 2    5, 2, 1

## Ideally I would like it to look like this:
 A B C D E
1 1 3 4 7 5 
2 1 3 4 7 3
3 1 3 4 7 2
4 1 3 4 7 1
5 2 5 3 9 5
6 3 4 5 2 5,
7 3 4 5 2 5 
8 3 4 5 2 2
9 3 4 5 2 1

有没有简单的方法来做到这一点?

【问题讨论】:

  • tidyr::unnest
  • 特别是像这样的问题,您需要给出一个可重现的示例,而不仅仅是对象外观的表示。一些指导:stackoverflow.com/a/28481250
  • 在基础 R 中:data.frame(df[rep(1:nrow(df), lengths(df$E)), 1:4], E = unlist(df$E), row.names = NULL)
  • 这不是它被列为重复的问题的重复。请重新打开它或选择一个实际重复的问题。

标签: r


【解决方案1】:

非常简单。假设您的数据框名为df

library(tidyr)
df %>% unnest(E)

数据:

structure(list(A = 1:3, B = c(3L, 5L, 4L), C = c(4L, 3L, 5L), 
D = c(7L, 9L, 2L), E = list(c(5, 3, 2, 1), 5, c(5, 2, 1))), .Names = c("A", 
"B", "C", "D", "E"), row.names = c(NA, -3L), class = "data.frame")

【讨论】:

    【解决方案2】:

    可能不是最短的方法,但这将获得您想要的结果,而无需依赖额外的库。

    首先定义数据集本身,正如你所描述的

    testdata<-t(matrix(list(1,3,4,7,c(5,3,2,1),
                          2,5,3,9,5,
                          3,4,5,2,c(5,2,1)
                          ),nrow=5))
    
    colnames(testdata)<-c("A","B","C","D","E")
    
    rownames(testdata)<-c(1,2,3)
    

    testdata如下,其中Numeric,4c(5,3,2,1)Numeric,3c(5,2,1)

      A B C D E        
    1 1 3 4 7 Numeric,4
    2 2 5 3 9 5        
    3 3 4 5 2 Numeric,3
    

    expandall 函数是多余的,但它有助于将代码分解成更易读的块。

    expandall<-function(x){
        do.call(cbind,x)
    }
    
    result<-apply(testdata,1,expandall)
    if(is.list(result)){ ## if there are sub arrays then apply will return 
                         ## a list
        result<-do.call(rbind,result)
    }
    

    对每一行数据应用expandall并绑定我们得到的结果

         A B C D E
    [1,] 1 3 4 7 5
    [2,] 1 3 4 7 3
    [3,] 1 3 4 7 2
    [4,] 1 3 4 7 1
    [5,] 2 5 3 9 5
    [6,] 3 4 5 2 5
    [7,] 3 4 5 2 2
    [8,] 3 4 5 2 1
    

    【讨论】:

      猜你喜欢
      • 2016-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-13
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多