r - 受试者重复输入数据库的长格式数据。您如何在 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)
这是预期的输出: 在此处输入图像描述
解决方案
这是你想要的?
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 )
推荐阅读
- php - AWS Codestar Laravel EB - Artisan 文件不正确
- actionscript-3 - 清除 DisplayObject() 而不给出对象名称
- execute - 如何为 select where 子句编写动态 SQL 查询?
- nativescript - 阅读 WebView 内容
- c++ - 有谁知道这个while循环有什么问题?
- html - 幻灯片中的所有内容重叠
- javascript - 通过 eventHandler 更新状态
- php - PHP 在许多 php 文件中保存会话
- ruby-on-rails - 如何从 Rails 索引视图中的一对多关系表中获取最后更新日期
- h2o - H2o 模型训练指标日志位置