我有
dat <-data.frame(study=letters[c(1,1,1,4,4,4,4,10,10)],n1i=c(25,25,22,38,50,30,30,50,50))
我想要
study n1i grp
1 a 25 A
2 a 25 A
3 a 22 B
4 d 38 A
5 d 50 B
6 d 30 C
7 d 30 C
8 j 50 A
9 j 50 A
但是这个...
dat$grp<-
as.vector(unlist(aggregate(dat$n1i,
list(dat$study), function(x) LETTERS[1:length(x)])$x))
...给我
> dat
study n1i grp
1 a 25 A
2 a 25 B
3 a 22 C
4 d 38 A
5 d 50 B
6 d 30 C
7 d 30 D
8 j 50 A
9 j 50 B
换句话说,我希望“grp”字母从 1 到最后一个唯一的 study*n1i 组合。
最佳答案
dat <-data.frame(study=letters[c(1,1,1,4,4,4,4,10,10)],n1i=c(25,25,22,38,50,30,30,50,50))
library(dplyr)
dat %>%
group_by(study) %>% # for each study
mutate(id = row_number()) %>% # get the number of row as an id
group_by(study, n1i) %>% # for each study and n1i combination
transmute(grp = LETTERS[min(id)]) %>% # add the letters based on the minimum id value of that combination, while removing the id column
ungroup() # forget the grouping
# # A tibble: 9 x 3
# study n1i grp
# <fct> <dbl> <chr>
# 1 a 25 A
# 2 a 25 A
# 3 a 22 C
# 4 d 38 A
# 5 d 50 B
# 6 d 30 C
# 7 d 30 C
# 8 j 50 A
# 9 j 50 A
这种方法假设重复的行一个接一个。
关于r - 带有代表其他向量的独特组合的字母的新向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50761132/