我有一个数据框架,如下所示:
df <- data.frame(
id = c(1, 2, 3, 4, 5),
generation = as.factor(c(3, 2, 4, 3, 4)),
income = as.factor(c(4, 3, 3, 7, 3)),
fem = as.factor(c(0, 0, 1, 0, 1))
)其中id是数据集中个体的标识符,generation、income和fem是个体的分类特征。现在,我想根据个人特征将个人归入队列(“组”),其中对个人特征具有完全相同值的个体应该得到相同的cohort_id。因此,我希望得到以下结果:
data.frame(
id = c(1, 2, 3, 4, 5),
generation = as.factor(c(3, 2, 4, 3, 4)),
income = as.factor(c(4, 3, 3, 7, 3)),
fem = as.factor(c(0, 0, 1, 0, 1)),
cohort_id = as.factor(c(1, 2, 3, 4, 3))
)请注意,id =3和id =5得到的cohort_id与它们具有相同的特征相同。
我的问题是,是否有一种快速的方法来创建cohort_id,而不必一次又一次地使用多个case_when或ifelse?如果您想要构建许多队列,这可能会变得非常乏味。使用dplyr的解决方案很好,但没有必要。
发布于 2021-12-16 16:41:41
有多种方法可以做到这一点-一种选择是使用paste值对列和match进行unique
library(dplyr)
library(stringr)
df %>%
mutate(cohort_id = str_c(generation, income, fem),
cohort_id = match(cohort_id, unique(cohort_id)))-output
id generation income fem cohort_id
1 1 3 4 0 1
2 2 2 3 0 2
3 3 4 3 1 3
4 4 3 7 0 4
5 5 4 3 1 3发布于 2021-12-16 18:15:57
以下代码将创建一个索引“cohort_id”,其值与所提供的预期值略有不同,但符合分组规则:
library(dplyr)
df %>% group_by(generation, income, fem) %>%
mutate(cohort_id = cur_group_id())%>%
ungroup()
# A tibble: 5 × 5
id generation income fem cohort_id
<dbl> <fct> <fct> <fct> <int>
1 1 3 4 0 2
2 2 2 3 0 1
3 3 4 3 1 4
4 4 3 7 0 3
5 5 4 3 1 4https://stackoverflow.com/questions/70382569
复制相似问题