MWE。
df <- tibble(ID = c(1:12),
Group = c(rep(1,3), rep(2,3), rep(3,3), rep(4,3)),
Choice = c( rep(1.5, 3), round(rnorm(n=9,mean=10,sd=5), digits = 1) )
)
我想要的是确定每个小组中小组成员的决定是否相同。所需的输出应该类似于:
df <- tibble(ID = c(1:12),
Group = c(rep(1,3), rep(2,3), rep(3,3), rep(4,3)),
Choice = c( rep(1.5, 3), round(rnorm(n=9,mean=10,sd=5), digits = 1) ),
Symmetric = c ( rep(1, 3), rep(0, 9) )
)
有没有快速简单的解决方案?非常感谢!
> df %>% mutate(Symmetric = +(var(Choice) == 0), .by = Group)
# A tibble: 12 × 4
ID Group Choice Symmetric
<int> <dbl> <dbl> <int>
1 1 1 1.5 1
2 2 1 1.5 1
3 3 1 1.5 1
4 4 2 16.6 0
5 5 2 6.4 0
6 6 2 7.5 0
7 7 3 13.7 0
8 8 3 16 0
9 9 3 8.2 0
10 10 4 2 0
11 11 4 9.2 0
12 12 4 15.1 0
几个想法 -
library(dplyr)
df %>% mutate(Symmetric = as.integer(n_distinct(Choice) == 1), .by = Group)
以 R 为基数:
transform(df, Symmetric = as.integer(ave(Choice, Group, FUN = \(x) length(unique(x)) == 1)))
Choice
是一个数值,我们还可以检查它的标准差 sd
df %>% mutate(Symmetric = as.integer(sd(Choice) == 0), .by = Group)
以 R 为基数:
transform(df, Symmetric = as.integer(ave(Choice, Group, FUN = sd) == 0))
全部返回:
# ID Group Choice Symmetric
#1 1 1 1.5 1
#2 2 1 1.5 1
#3 3 1 1.5 1
#4 4 2 9.7 0
#5 5 2 -0.2 0
#6 6 2 12.9 0
#7 7 3 23.7 0
#8 8 3 2.3 0
#9 9 3 12.5 0
#10 10 4 7.5 0
#11 11 4 2.0 0
#12 12 4 14.0 0
选择值的方差将为 0 当且仅当它们相同并且!会将其转换为 TRUE,+ 将其转换为 1。
library(dplyr)
df %>% mutate(Symmetric = +!var(Choice), .by = Group)
给予
# A tibble: 12 × 4
ID Group Choice Symmetric
<int> <dbl> <dbl> <int>
1 1 1 1.5 1
2 2 1 1.5 1
3 3 1 1.5 1
4 4 2 22.6 0
5 5 2 12.7 0
6 6 2 11.2 0
7 7 3 4.8 0
8 8 3 16.5 0
9 9 3 14.1 0
10 10 4 9.7 0
11 11 4 6.1 0
12 12 4 6.3 0