【发布时间】:2020-03-21 17:49:11
【问题描述】:
data=data.frame("StudentID" = c(1,1,1,2,2,2,3,3,3),
"Grade"=c(1,2,3,1,2,3,1,2,3),
"Score" = c(1,2,5,2,4,3,1,2,2))
我有“数据”,想在哪里制作“数据1”
data1=data.frame("StudentID" = c(1,1,1,2,2,2,3,3,3),
"Grade"=c(1,2,3,1,2,3,1,2,3),
"Score" = c(1,2,5,2,4,3,1,2,2),
"Flag"=c(0,0,0,1,1,1,2,2,2))
Flag 的作用是表明Grade 处的Score 是否有StudentID 处的G 高于G-1。换句话说,我们预计分数只会随着年级的增加而上升。
- 如果有任何
Score值随着Grade变高而下降,则Flag等于1。并列分数应以2表示。 - 如果学生在
Grade、2和3中的得分为2,则为Flag == 2。 - 如果
Scores仅随着Grade的上升而上升,那么Flag == 0。
使用@akron 完美答案,library(data.table) setDT(data)[, flag := fifelse(any(diff(Score) 0, 2, 0)) , .(StudentID)]
现在说我有一个学生的标志 2。如何通过加 1 更新他们的 SECOND 连续分数。
使用上面的data1
data1=data.frame("StudentID" = c(1,1,1,2,2,2,3,3,3),
"Grade"=c(1,2,3,1,2,3,1,2,3),
"Score" = c(1,2,5,2,4,3,1,2,2),
"Flag"=c(0,0,0,1,1,1,2,2,2),
"Score2" = c(1,2,5,2,4,3,1,2,3))
【问题讨论】:
-
您的解释和
data1之间存在差异,即我没有看到2应该在哪里? -
你需要
library(dplyr);data1 %>% group_by(StudentID) %>% mutate(ind = case_when(any(diff(Score) < 0) ~ 1, all(2:3 %in% Grade[Score == 2]) ~ 2, TRUE ~ 0 )) -
或
dat.atablesetDT(data)[, flag := fifelse(any(diff(Score)
标签: r data.table data-manipulation