我正在处理一个数据集,其中有学生对教师的评分。有些学生给同一个老师打分不止一次。对于这些数据,我要做的是按照以下标准对其进行子集:
1)保留学生的唯一身份和评级。
2)学生对教师进行两次评分的情况下,只保留一个评分,但随机选择要保持的评分。
3)如果可能的话,我希望能够在每个分析文件的顶部以一个咀嚼脚本运行代码,并确保为每个分析创建的数据集完全相同(set seed?)。
# data
student.id <- c(1,1,2,3,3,4,5,6,7,7,7,8,9)
teacher.id <- c(1,1,1,1,1,2,2,2,2,2,2,2,2)
rating <- c(100,99,89,100,99,87,24,52,100,99,89,79,12)
df <- data.frame(student.id,teacher.id,rating)感谢对如何向前迈进的任何指导。
发布于 2016-07-21 18:41:47
假设每个student.id只应用于一名教师,则可以使用以下方法。
# get a list containing data.frames for each student
myList <- split(df, df$student.id)
# take a sample of each data.frame if more than one observation or the single observation
# bind the result together into a data.frame
set.seed(1234)
do.call(rbind, lapply(myList, function(x) if(nrow(x) > 1) x[sample(nrow(x), 1), ] else x))这会返回
student.id teacher.id rating
1 1 1 100
2 2 1 89
3 3 1 99
4 4 2 87
5 5 2 24
6 6 2 52
7 7 2 99
8 8 2 79
9 9 2 12如果同一student.id对多个教师进行评分,则此方法需要构造一个带有interaction函数的新变量:
# create new interaction variable
df$stud.teach <- interaction(df$student.id, df$teacher.id)
myList <- split(df, df$stud.teach)然后,代码的其余部分与上面的代码相同。
一个可能更快的方法是使用data.table库和rbindlist。
library(data.table)
# convert into a data.table
setDT(df)
myList <- split(df, df$stud.teach)
# put together data.frame with rbindlist
rbindlist(lapply(myList, function(x) if(nrow(x) > 1) x[sample(nrow(x), 1), ] else x))发布于 2022-02-11 14:43:23
现在,使用data.table可以更快地完成这一任务。您的问题相当于从组内取样行,请参阅
https://stackoverflow.com/questions/38511874
复制相似问题