【问题标题】:creating a new column with unique id numbers创建一个具有唯一 ID 号的新列
【发布时间】:2020-10-22 07:27:54
【问题描述】:

我的数据框看起来像这样,但实际上每个参与者总共有 24 个项目,总共有 99 个参与者。 “类”变量“a”、“b”和“c”也有 3 个级别。

First  Last  Class  Item  Answer
bob    smith a      1     b
bob    smith a      2     a
bob    smith a      3     a
jane   jones a      1     c
jane   jones a      2     a
jane   jones a      3     b

我想要的是创建一个列 'Unique_ID' 列,如下所示:

Unique_ID First  Last  Class  Item  Answer
1a        bob    smith a      1     b
1a        bob    smith a      2     a
1a        bob    smith a      3     a
2a        jane   jones a      1     c
2a        jane   jones a      2     a
2a        jane   jones a      3     b

我希望将他们所属的“班级”包含在 ID 号中。

有什么建议吗?谢谢!

【问题讨论】:

  • 如果您在一个班级中有两个同名的人怎么办,或者我们可以假设您没有?
  • 我碰巧知道没有,因为它不是一个巨大的数据集,我已经手动检查过。我想如果他们是一种检查方法也会有帮助。

标签: r data-manipulation


【解决方案1】:

假设名字和姓氏的组合是唯一的,您可以创建一个唯一的 ID,如下所示。

library(dplyr)

df %>%
  mutate(Name = paste(First, Last), 
         Unique_ID = paste0(match(Name, unique(Name)), Class))

#  First  Last Class Item Answer       Name Unique_ID
#1   bob smith     a    1      b  bob smith        1a
#2   bob smith     a    2      a  bob smith        1a
#3   bob smith     a    3      a  bob smith        1a
#4  jane jones     a    1      c jane jones        2a
#5  jane jones     a    2      a jane jones        2a
#6  jane jones     a    3      b jane jones        2a

【讨论】:

    【解决方案2】:

    这是基础 R 中应该完成任务的单行代码:

    within(df, Unique_ID <- paste0(as.numeric(factor(paste(First, Last))), Class))
    #>   First  Last Class Item Answer Unique_ID
    #> 1   bob smith     a    1      b        1a
    #> 2   bob smith     a    2      a        1a
    #> 3   bob smith     a    3      a        1a
    #> 4  jane jones     a    1      c        2a
    #> 5  jane jones     a    2      a        2a
    #> 6  jane jones     a    3      b        2a
    

    【讨论】:

      【解决方案3】:

      这行得通吗:

      > library(dplyr)
      > df %>% group_by(First, Last) %>% 
      +   mutate(Id = as.character(cur_group_id())) %>% 
      +   mutate(Unique_ID = paste0(Id, Class)) %>% 
      +   select(-Id) %>% relocate(6,1:5)
      # A tibble: 6 x 6
      # Groups:   First, Last [2]
        Unique_ID First Last  Class  Item Answer
        <chr>     <chr> <chr> <chr> <dbl> <chr> 
      1 1a        bob   smith a         1 b     
      2 1a        bob   smith a         2 a     
      3 1a        bob   smith a         3 a     
      4 2a        jane  jones a         1 c     
      5 2a        jane  jones a         2 a     
      6 2a        jane  jones a         3 b     
      > 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-24
        • 2015-11-15
        • 2016-11-16
        • 2013-04-29
        相关资源
        最近更新 更多