我遇到麻烦(可能因为我是dplyr的新手)试图重新编码值.我试图按编号拆分参与者,然后将日期值重新编码为1,依此类推.目前是一个月中的某一天....我的目标是让它成为实验的一天.注意:参与者列出的第一个日期应为第1天.
我的尝试:
df<-data.frame(participant_number=c(1,1,1,2,2),month=c(3,3,4,3,3),day=c(6,6,1,7,8))
res<-setDT(df) %>% group_by(participant_number) %>% day
Run Code Online (Sandbox Code Playgroud)
我的目标:
participant_number day month recoded_day
1 6 3 1
1 6 3 1
1 1 4 2
2 7 3 1
2 8 3 2
Run Code Online (Sandbox Code Playgroud)
我setDT()在你的代码中看到,所以这里是一个完整的data.table解决方案,以备你感兴趣.
library(data.table)
setDT(df)[,
recoded_day := cumsum(c(1, diff(as.IDate(paste(month, day), "%m %d")))),
by = participant_number
]
Run Code Online (Sandbox Code Playgroud)
这给了我们
participant_number month day recode_day
1: 1 3 6 1
2: 1 3 6 1
3: 1 4 1 27
4: 2 3 7 1
5: 2 3 8 2
Run Code Online (Sandbox Code Playgroud)