我写了一些非常非常难看的代码来执行数据转换。我知道它可能可以被矢量化并显着加速,但我不确定如何。
我拥有的数据如下所示:
scores<-as.data.frame(cbind(c(1,2,3,3,1,2,3,1,2,1,2,3),c(5,5,5,5,6,6,6,7,7,8,8,8),
c(0,1,1,1,1,0,1,.5,"fickle",1,2.2,1),c(1,1,1,2,1,1,1,1,1,1,1,1)))
names(dat)<-c("name","question_id","correct","attempt")
ids<-c(5,7,8)
我想要的是创建一个 studentXquestion 矩阵,显示他们对 ids 向量中包含的每个问题的最终尝试分数。如果学生没有完成该问题,它也会给出 NA,如果“正确”列中出现 0 或 1 以外的其他值,它也会给出 99,因为某些数据有点难看。
以下是我到目前为止的代码。
students<-unique(scores$name)
finaldat<-data.frame(matrix(ncol=length(ids),nrow=length(unique(students))))
for(i in 1:length(students)){
for(j in 1:length(ids)){
attempts<-which(scores$question_id==ids[j] &
scores$name==students[i])
if(length(attempts)==0){finaldat[i,j]<-NA}
else{
last.score<-as.numeric(scores$correct[attempts[which(attempts==length(attempts))]])
finaldat[i,j]<-99
if(length(last.score)==0){finaldat[i,j]<-NA}
else{if(last.score==0 | last.score==1){
finaldat[i,j]<-last.score
}
}
}
}
}
finaldat
除了运行速度非常慢之外,它也不起作用,因为我无法将头绕在 last.score 行上。我敢肯定有一个整洁的经文解决方案,但我很难过。任何提示将不胜感激。
所以输出数据将是:
cbind(c(0,1,1),c(99,99,NA),c(1,99,1))
我们可以看到问题 6 已被排除,任何非二进制都已转换为 99,缺失值是 NA,只保留了最后的尝试。