【问题标题】:Creating factor from multiple other factors fast快速从多个其他因素中创建因素
【发布时间】:2022-01-19 18:05:10
【问题描述】:

我有一个如下所示的数据框:

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 是数据集中个人的标识符,generationincomefem 是个人的分类特征。现在,我想根据个人特征将个人放入群组(“组”),其中个人特征值完全相同的个人应该得到相同的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_ids,而无需一遍又一遍地使用多个case_whenifelse?如果您想建立许多群组,这可能会变得非常乏味。使用dplyr 的解决方案会很好,但不是必需的。

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    以下代码将创建一个索引“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             4
    

    【讨论】:

      【解决方案2】:

      有多种方法可以做到这一点 - 一种选择是 paste 列和 matchunique

      library(dplyr)
      library(stringr)
      df %>%
           mutate(cohort_id = str_c(generation, income, fem), 
                  cohort_id = match(cohort_id, unique(cohort_id)))
      

      -输出

       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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-10-14
        • 1970-01-01
        • 1970-01-01
        • 2023-01-19
        • 2019-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多