将列的所有值汇总到向量中

时间:2017-12-20 10:39:39

标签: r tibble

所以这是我仍然想要做的事情。

想象一下像这样的人:

library(tidyverse)
t1 <- tibble(
  id       = c(1,1,1,1,2,2,2,2,2),
  id_sub   = c(1,1,2,2,1,2,2,2,2),
  position = c(1,2,1,2,1,1,2,3,4),
  head     = c(1,1,2,2,1,3,2,2,3)
  )

我想要实现的是创建第5个属性depend,其中每个head的值都来自id_sub。这意味着,depend的每个值都是一个最小长度为1的向量(对于tibble来说应该不是问题,对吧?)。

我在这个例子中寻找的结果将有一个带有以下向量的属性:

c(1,1),c(2,2),c(1),c(3,2,2,3)

当然,我的数据有点大,到目前为止,我能找到的唯一解决方案是对tibble进行分组并传播positionhead

t1 %>% 
  group_by(id, id_sub) %>% 
  spread(position, head)

这当然会创建多个属性:

# A tibble: 4 x 6
# Groups:   id, id_sub [4]
     id id_sub   `1`   `2`   `3`   `4`
* <dbl>  <dbl> <dbl> <dbl> <dbl> <dbl>
1     1      1     1     1    NA    NA
2     1      2     2     2    NA    NA
3     2      1     1    NA    NA    NA
4     2      2     3     2     2     3

对于一个样本,我可以将position x head转换为矩阵,并将其转换为忽略NA的向量。但这对我的规模没有帮助。

m <- t1 %>% 
  filter(id == 2 & id_sub == 2) %>% 
  select(-c(id,id_sub)) %>% 
  spread(position, head) %>% 
  as.matrix()
m <- as.vector(m)
m[!is.na(m)]

具有以下结果:

[1] 3 2 2 3

很高兴听到您的想法和建议!

2 个答案:

答案 0 :(得分:4)

这样做你想要的吗?

library(data.table)
split(t1$head, rleid(t1$id_sub))

输出:

$`1`
[1] 1 1

$`2`
[1] 2 2

$`3`
[1] 1

$`4`
[1] 3 2 2 3

答案 1 :(得分:4)

另一种可能的解决方案:

t1 %>% 
  group_by(data.table::rleid(id_sub)) %>% 
  summarise(hd = list(head)) %>% 
  pull(hd)

给出:

[[1]]
[1] 1 1

[[2]]
[1] 2 2

[[3]]
[1] 1

[[4]]
[1] 3 2 2 3
相关问题