R - 按变量分组,然后分配唯一ID

时间:2016-09-22 23:47:27

标签: r dplyr

我感兴趣的是去除具有时间固定和时间变量值的敏感数据集。我想(a)按社会安全号码对所有案件进行分组,(b)为这些案件分配一个唯一的ID,然后(c)删除社会安全号码。

以下是一个示例数据集:

personal_id    gender  temperature
111-11-1111      M        99.6
999-999-999      F        98.2
111-11-1111      M        97.8
999-999-999      F        98.3
888-88-8888      F        99.0
111-11-1111      M        98.9

非常感谢任何解决方案。

3 个答案:

答案 0 :(得分:27)

dplyr具有group_indices功能,可用于创建唯一的群组ID

library(dplyr)
data <- data.frame(personal_id = c("111-111-111", "999-999-999", "222-222-222", "111-111-111"),
                       gender = c("M", "F", "M", "M"),
                       temperature = c(99.6, 98.2, 97.8, 95.5))

data$group_id <- data %>% group_indices(personal_id) 
data <- data %>% select(-personal_id)

data
  gender temperature group_id
1      M        99.6        1
2      F        98.2        3
3      M        97.8        2
4      M        95.5        1

或在同一管道(https://github.com/tidyverse/dplyr/issues/2160)内:

data %>% 
    mutate(group_id = group_indices(., personal_id))

答案 1 :(得分:9)

dplyr::group_indices()起,不推荐使用

dplyr 1.0.0。应改为使用dplyr::cur_group_id()

df %>%
 group_by(personal_id) %>%
 mutate(group_id = cur_group_id())

  personal_id gender temperature group_id
  <chr>       <chr>        <dbl>    <int>
1 111-11-1111 M             99.6        1
2 999-999-999 F             98.2        3
3 111-11-1111 M             97.8        1
4 999-999-999 F             98.3        3
5 888-88-8888 F             99          2
6 111-11-1111 M             98.9        1

答案 2 :(得分:0)

使用dplyr包:

library(dplyr)
data <- data.frame(personal_id = c("111-111-111", "999-999-999", "222-222-222", "111-111-111"),
                 gender = c("M", "F", "M", "M"),
                 temperature = c(99.6, 98.2, 97.8, 95.5))

首先提取personal_id以创建唯一ID:

cases <- data.frame(levels = levels(data$personal_id))

使用rownames,您将获得唯一标识符:

cases <- cases %>%
    mutate(id = rownames(cases))

结果:

       levels id
1 111-111-111  1
2 222-222-222  2
3 999-999-999  3

然后您将案例数据框与您的数据一起加入:

data <- left_join(data, cases, by = c("personal_id" = "levels"))

通过粘贴使用性别生成的ID来创建更加唯一的ID:

mutate(UID = paste(id, gender, sep=""))

最后删除了personal_id和简单的id:

select(-personal_id, -id)

然后你去:):

data <- left_join(data, cases, by = c("personal_id" = "levels")) %>%
        mutate(UID = paste(id, gender, sep="")) %>%
        select(-personal_id, -id)

结果:

  gender temperature UID
1      M        99.6  1M
2      F        98.2  3F
3      M        97.8  2M
4      M        95.5  1M