简体   繁体   English

R 按组查找两个值之间的距离

[英]R Find Distance Between Two values By Group

HAVE = data.frame(INSTRUCTOR = c(1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3),
STUDENT = c(1, 2, 2, 2, 1, 3, 1, 1, 1, 1, 2, 1),
SCORE = c(10, 1, 0, 0, 7, 3, 5, 2, 2, 4, 10, 2),
TIME = c(1,1,2,3,2,1,1,2,3,1,1,2))
 
WANT = data.frame(INSTRUCTOR = c(1, 2, 3), 
SCORE.DIF = c(-9, NA, 6))

For each INSTRUCTOR, I wish to find the SCORE of the first and second STUDENT, and subtract their scores.对于每个 INSTRUCTOR,我希望找到第一名和第二名 STUDENT 的 SCORE,然后减去他们的分数。 The STUDENT code varies so I wish not to use '==1' vs '==2'学生代码各不相同,所以我不希望使用“==1”与“==2”

I try:我尝试:

HAVE[, .SD[1:2], by = 'INSTRUCTOR']

but do not know how to subtract vertically and obtain 'WANT' data frame from 'HAVE'但不知道如何垂直减去并从 'HAVE' 获得 'WANT' 数据框

library(data.table)
setDT(HAVE)
unique(HAVE, by = c("INSTRUCTOR", "STUDENT")
  )[, .(SCORE.DIF = diff(SCORE[1:2])), by = INSTRUCTOR]
#    INSTRUCTOR SCORE.DIF
#         <num>     <num>
# 1:          1        -9
# 2:          2        NA
# 3:          3         6

To use your new TIME variable, we can do要使用您的新TIME变量,我们可以这样做

HAVE[, .SD[which.min(TIME),], by = .(INSTRUCTOR, STUDENT)
  ][, .(SCORE.DIF = diff(SCORE[1:2])), by = INSTRUCTOR]
#    INSTRUCTOR SCORE.DIF
#         <num>     <num>
# 1:          1        -9
# 2:          2        NA
# 3:          3         6

One might be tempted to replace SCORE[1:2] with head(SCORE,2) , but that won't work: head(SCORE,2) will return length-1 if the input is length-2, as it is with instructor 2 (who only has one student albeit multiple times).人们可能会想用head(SCORE,2)替换SCORE[1:2] ,但这行不通:如果输入的长度为 2, head(SCORE,2)将返回 length-1,就像讲师 2(虽然有多次,但只有一名学生)。 When you run diff on length-1 (eg, diff(1) ), it returns a 0-length vector, which in the above data.table code reduces to zero rows for instructor 2. However , when there is only one student, SCORE[1:2] resolves to c(SCORE[1], NA) , for which the diff is length-1 (as needed) and NA (as needed).当您在长度为 1(例如diff(1) )上运行diff时,它会返回一个长度为 0 的向量,在上面的data.table代码中,对于教师 2,该向量减少为零行。但是,当只有一个学生时, SCORE[1:2]解析为c(SCORE[1], NA) ,diff 为 length-1(根据需要)和NA (根据需要)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM