将一列的所有值汇总到一个向量中
Summarise all values of a column into a vector
所以这是我仍在努力纠正的问题。
想象一下像这样的小标题:
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
,每个 id_sub
具有来自 head
的值。这确实意味着 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
很高兴听到您的想法和建议!
这是你想要的吗?
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
另一个可能的解决方案:
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(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
,每个 id_sub
具有来自 head
的值。这确实意味着 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
很高兴听到您的想法和建议!
这是你想要的吗?
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
另一个可能的解决方案:
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