展平包含R中列表的向量

时间:2016-12-06 19:49:31

标签: r

我正在尝试展平包含多个列表的向量。在保留与该列表相关的数据的同时,最好的方法是什么?我尝试使用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

有一种简单的方法吗?

2 个答案:

答案 0 :(得分:2)

很简单。假设您的数据框名为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")

答案 1 :(得分:1)

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

首先定义数据集本身,如您所述

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
相关问题