[英]Count in how many different groups I can find an element in R dplyr
我的数据看起来像这样
library(tidyverse)
df3 <- tibble(fruits=c("apple","banana","ananas","apple","ananas","apple","ananas"),
position=c("135","135","135","136","137","138","138"),
counts = c(100,200,100,30,40,50,100))
df3
#> # A tibble: 7 × 3
#> fruits position counts
#> <chr> <chr> <dbl>
#> 1 apple 135 100
#> 2 banana 135 200
#> 3 ananas 135 100
#> 4 apple 136 30
#> 5 ananas 137 40
#> 6 apple 138 50
#> 7 ananas 138 100
由reprex package (v2.0.1) 创建于 2022-02-21
我想group_by水果并计算每个水果属于哪个以及多少个不同的位置。 我希望我的数据看起来像
fruits groups n_groups sum_count
apple 135,136,138 3 180
banana 135 1 200
ananas 135,137,138 3 240
groups 列可以是字符列表。 我不太关心结构。
感谢您的时间。 任何指导表示赞赏。
我真的不明白你想要从你的描述中得到什么,但你可以通过fruits
分组来完成你想要的data.frame
:
df3 %>%
group_by(fruits) %>%
summarise(groups = list(position), n_groups = n(), counts = sum(counts))
fruits groups n_groups counts
<chr> <list> <int> <dbl>
1 ananas <chr [3]> 3 240
2 apple <chr [3]> 3 180
3 banana <chr [1]> 1 200
请在下面找到另一种使用data.table
可能性
代表
library(data.table)
library(tibble)
setDT(df3)[, .(groups = paste(position, collapse = ","), n_groups = .N, sum_count = sum(counts)) , by = .(fruits)]
#> fruits groups n_groups sum_count
#> 1: apple 135,136,138 3 180
#> 2: banana 135 1 200
#> 3: ananas 135,137,138 3 240
由reprex package (v2.0.1) 创建于 2022-02-21
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.