R 按组对新变量的数据表解决方案

R 按组对新变量的数据表解决方案,r,dplyr,data.table,R,Dplyr,Data.table,缺少“时间”的更新数据 dataHAVE=data.frame("student"=c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5), "score"=c(0,8,8,7,9,4,9,2,7,NA,4,7,NA,NA,NA), "time"=c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3)) 根据显示的逻辑,可以使用data.table dataHAVE=data.frame("st

缺少“时间”的更新数据

dataHAVE=data.frame("student"=c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5),
                    "score"=c(0,8,8,7,9,4,9,2,7,NA,4,7,NA,NA,NA),
                    "time"=c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3))

根据显示的逻辑,可以使用
data.table

dataHAVE=data.frame("student"=c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7),
                    "score"=c(0,8,8,7,9,4,9,2,7,NA,4,7,NA,NA,NA,6,9,3,NA,NA,NA),
                    "time"=c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,NA,2,NA,NA,NA,NA))
库(data.table)
setDT(dataHAVE)[,c(“score3”、“timescore3”、“score7”、“timescore7”):={

sc3第二个条件不清楚
库(data.table)setDT(dataHAVE)[,c(“score3”,“score7”):=.(+(任意(score@akron相当惊人!关于:如何做到这一点并忽略缺失的NA值的最后询问?在您的示例中,我没有得到NA,但如果分数中有NA元素,
NA.rm=TRUE
in
min
max
@akrun非常感谢我在尝试缺失VAL的数据时添加了NA.rm=TRUE和min(time[sc3],na.rm=TRUE)i get::缺少值,其中TRUE/FALSE neededIt可能是该特定.group的所有元素都是na的情况,在这种情况下,您需要
if(all(is.na(time[sc3]))na else min(time[sc3],na.rm=TRUE)
我添加了更新的数据文件以解决我提出的问题,即每个学生都有一些NA,而一个学生的所有NA都是。@b由于您的示例数据已更新,我非常感谢您。但是对于学生5,所有新变量都应为“NA”,因为没有数据。我认为我发现了问题,即:一些学生的变量丢失了g数据准时!我尝试了一个min((time,na.rm=TRUE)[sc7],na.rm=TRUE)的解决方案,但没有成功。非常感谢您的帮助-您的帮助令人难以置信!!我添加了一个新示例
dataHAVE=data.frame("student"=c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7),
                    "score"=c(0,8,8,7,9,4,9,2,7,NA,4,7,NA,NA,NA,6,9,3,NA,NA,NA),
                    "time"=c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,NA,2,NA,NA,NA,NA))
library(data.table)
setDT(dataHAVE)[,c("score3", "timescore3", "score7", "timescore7") := {
                   sc3 <- score <=3
                   sc7 <-  score <= 7
                   tsc3 <- if(any(sc3)) min(time[sc3]) else max(time)
                   tsc7 <- if(any(sc7)) min(time[sc7]) else max(time)
         .(+(any(sc3)), tsc3, +(any(sc7)),tsc7 )}, .(student)]
setDT(dataHAVE)[,c("score3", "timescore3", "score7", "timescore7") := {
                   sc3 <- score <=3 & !is.na(score)
                    sc7 <-  score <= 7 & !is.na(score)
                    tsc3 <- if(any(sc3)) min(time[sc3], na.rm = TRUE) else max(time, na.rm = TRUE)
                    tsc7 <- if(any(sc7)) min(time[sc7], na.rm = TRUE) else max(time, na.rm = TRUE)
          .(+(any(sc3)), tsc3, +(any(sc7)),tsc7 )}, .(student)]