根据条件为组计算数据框的不同级别
count distinct levels of a data frame for groups based on a condition
我有以下DF
x = data.frame('grp' = c(1,1,1,2,2,2),'a' = c(1,2,1,1,2,1), 'b'= c(6,5,6,6,2,6), 'c' = c(0.1,0.2,0.4,-1, 0.9,0.7))
grp a b c
1 1 1 6 0.1
2 1 2 5 0.2
3 1 1 6 0.4
4 2 1 6 -1.0
5 2 2 2 0.9
6 2 1 6 0.7
我想为 c >= 0.1
的每个组计算 (a,b)
的不同水平
我已经尝试使用 dplyr
为此使用 group_by
& summarise
但没有得到想要的结果
x %>% group_by(grp) %>% summarise(count = n_distinct(c(a,b)[c >= 0.1]))
对于上述情况,我希望得到以下结果
grp count
<dbl> <int>
1 1 2
2 2 2
但是使用上面的查询我得到了以下结果
grp count
<dbl> <int>
1 1 4
2 2 3
从逻辑上讲,上面的输出似乎解决了 (a,b)
的连接列表的所有唯一值,但不是我所需要的
任何指点,非常感谢任何帮助
我们可以 paste
a
和 b
列并计算每组中的不同值。
library(dplyr)
x %>%
mutate(col = paste(a, b, sep = "_")) %>%
group_by(grp) %>%
summarise(count = n_distinct(col[c >= 0.1]))
# grp count
# <dbl> <int>
#1 1 2
#2 2 2
这是使用 dplyr
的另一种方法。听起来您想 filter
基于 c
,所以我们这样做了。 n_distinct
中不用c(a, b
),我们可以写成n_distinct(a, b)
.
x %>%
filter(c >= 0.1) %>%
group_by(grp) %>%
summarise(cnt_d = n_distinct(a, b))
# grp cnt_d
# <dbl> <int>
# 1 1 2
# 2 2 2
一个选项使用data.table
library(data.table)
setDT(x)[c >= 0.1, .(cnt_d = uniqueN(paste(a, b))), .(grp)]
# grp cnt_d
#1: 1 2
#2: 2 2
我有以下DF
x = data.frame('grp' = c(1,1,1,2,2,2),'a' = c(1,2,1,1,2,1), 'b'= c(6,5,6,6,2,6), 'c' = c(0.1,0.2,0.4,-1, 0.9,0.7))
grp a b c
1 1 1 6 0.1
2 1 2 5 0.2
3 1 1 6 0.4
4 2 1 6 -1.0
5 2 2 2 0.9
6 2 1 6 0.7
我想为 c >= 0.1
(a,b)
的不同水平
我已经尝试使用 dplyr
为此使用 group_by
& summarise
但没有得到想要的结果
x %>% group_by(grp) %>% summarise(count = n_distinct(c(a,b)[c >= 0.1]))
对于上述情况,我希望得到以下结果
grp count
<dbl> <int>
1 1 2
2 2 2
但是使用上面的查询我得到了以下结果
grp count
<dbl> <int>
1 1 4
2 2 3
从逻辑上讲,上面的输出似乎解决了 (a,b)
的连接列表的所有唯一值,但不是我所需要的
任何指点,非常感谢任何帮助
我们可以 paste
a
和 b
列并计算每组中的不同值。
library(dplyr)
x %>%
mutate(col = paste(a, b, sep = "_")) %>%
group_by(grp) %>%
summarise(count = n_distinct(col[c >= 0.1]))
# grp count
# <dbl> <int>
#1 1 2
#2 2 2
这是使用 dplyr
的另一种方法。听起来您想 filter
基于 c
,所以我们这样做了。 n_distinct
中不用c(a, b
),我们可以写成n_distinct(a, b)
.
x %>%
filter(c >= 0.1) %>%
group_by(grp) %>%
summarise(cnt_d = n_distinct(a, b))
# grp cnt_d
# <dbl> <int>
# 1 1 2
# 2 2 2
一个选项使用data.table
library(data.table)
setDT(x)[c >= 0.1, .(cnt_d = uniqueN(paste(a, b))), .(grp)]
# grp cnt_d
#1: 1 2
#2: 2 2