R 数据表重新格式化
我有数据“d1”,希望数据“d2”有规则: 学生:只有d1的学生 问题1:如果d1学生的分数曾经等于2,那么这等于1。如果不是,它等于0 VX:如果d1的分数曾经等于d1学生的3分,则等于1。如果不是,它等于0 A:等于学生从d1开始的一年级/最低年级 B:如果d1的分数等于2,那么就在这之前把分数记下来。如果没有,则输入最后/最大坡度。重要的是,一年级不能等于2,因此不必担心数据丢失 C:如果d1的分数等于2,那么在发生这种情况时就把分数记下来。如果没有,则输入最后/最大坡度 D:如果d1的分数等于3分,那么在发生这种情况时记下分数。如果没有,则输入最后/最大坡度 班级:仅d1中的班级R 数据表重新格式化,r,data.table,R,Data.table,我有数据“d1”,希望数据“d2”有规则: 学生:只有d1的学生 问题1:如果d1学生的分数曾经等于2,那么这等于1。如果不是,它等于0 VX:如果d1的分数曾经等于d1学生的3分,则等于1。如果不是,它等于0 A:等于学生从d1开始的一年级/最低年级 B:如果d1的分数等于2,那么就在这之前把分数记下来。如果没有,则输入最后/最大坡度。重要的是,一年级不能等于2,因此不必担心数据丢失 C:如果d1的分数等于2,那么在发生这种情况时就把分数记下来。如果没有,则输入最后/最大坡度 D:如果d1的分
学校:只要学校从d1开始在
数据表中
,我们就可以做到:
d1=data.frame("Student"=c(1,1,1,2,2,2,3,3,4,4,4),
"Score"=c(1,1,1,1,2,2,1,3,1,2,3),
"Grade"=c(5,6,7,3,4,5,2,4,7,8,9),
"Class"=c(1,1,1,1,1,1,2,2,1,1,1),
"School"=c(100,100,100,100,100,100,92,92,81,81,81))
d2=data.frame("Student"=c(1,2,3,4,5),
"Q1"=c(0,1,0,1),
"VX"=c(0,0,1,1),
"A"=c(5,3,2,7),
"B"=c(7,3,4,7),
"C"=c(7,4,4,8),
"D"=c(7,5,4,9),
"Class"=c(1,1,2,1),
"School"=c(100,100,92,81))
在这里使用
dplyr
在键入方面可能有点优势,因为我们可以参考先前创建的Q1
和VX
列
library(data.table)
setDT(d1)[,.(Q1 = as.integer(any(Score == 2)),
VX = as.integer(any(Score == 3)),
A = first(Grade),
B = if(any(Score == 2)) Grade[which.max(Score == 2) - 1] else max(Grade),
C = if(any(Score == 2)) Grade[which.max(Score == 2)] else max(Grade),
D = if(any(Score == 3)) Grade[which.max(Score == 3)] else max(Grade)),
.(Student, Class, School)]
# Student Class School Q1 VX A B C D
#1: 1 1 100 0 0 5 7 7 7
#2: 2 1 100 1 0 3 3 4 5
#3: 3 2 92 0 1 2 4 4 4
#4: 4 1 81 1 1 7 7 8 9
library(dplyr)
d1 %>%
group_by(Student, Class, School) %>%
summarise(Q1 = as.integer(any(Score == 2)),
VX = as.integer(any(Score == 3)),
A = first(Grade),
B = if(Q1) Grade[which.max(Score == 2) - 1] else max(Grade),
C = if(Q1) Grade[which.max(Score == 2)] else max(Grade),
D = if(VX) Grade[which.max(Score == 3)] else max(Grade))