所以这是我仍在努力做到的事情。
想象一下像这样的傻瓜:
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和传播position
和head
:
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
xhead
转换为矩阵并将其转换为忽略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
很高兴听到您的想法和建议!
另一种可能的方案
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
这样做你想要的吗?
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