首页 > 解决方案 > 受试者重复输入数据库的长格式数据。您如何在 R/dplyr 中为每个主题的每个事件创建唯一 ID?

问题描述

有一个结构长的数据集。唯一 ID 输入的时间跨度为 2-3 周。数据为长格式。唯一 ID 在不同的时间跨度进入数据集。我想为每个时间跨度创建一个唯一 ID。

df <- data.frame(id = rep(c("1","2","3","1"), each=2),
            counter=c(1,2,1,2,1,2,1,2),
            date_t=rep(seq(c(ISOdate(2021,3,20,9,7)), by = "day", length.out = 2),times=4),
            task=c("A","B","A","B","A","B","A","B"), stringsAsFactors=FALSE)

这是预期的输出: 在此处输入图像描述

标签: rdplyrpanel-dataunique-id

解决方案


这是你想要的?


library(dplyr)

df1 <- 
  df %>% 
  mutate(id_new = c(0, cumsum(abs(diff(as.numeric(id))))))

df1
#>   id counter              date_t task id_new
#> 1  1       1 2021-03-20 09:07:00    A      0
#> 2  1       2 2021-03-21 09:07:00    B      0
#> 3  2       1 2021-03-20 09:07:00    A      1
#> 4  2       2 2021-03-21 09:07:00    B      1
#> 5  3       1 2021-03-20 09:07:00    A      2
#> 6  3       2 2021-03-21 09:07:00    B      2
#> 7  1       1 2021-03-20 09:07:00    A      4
#> 8  1       2 2021-03-21 09:07:00    B      4

数据

df <- data.frame(id = rep(c("1","2","3","1"), each=2),
                 counter=c(1,2,1,2,1,2,1,2),
                 date_t=rep(seq(c(ISOdate(2021,3,20,9,7)), by = "day", length.out = 2),times=4),
                 task=c("A","B","A","B","A","B","A","B"), stringsAsFactors=FALSE)

reprex 包于 2021-04-12 创建 (v2.0.0 )


推荐阅读