【问题标题】:Select random rows from duplicate IDS从重复的 IDS 中选择随机行
【发布时间】:2016-07-21 18:32:53
【问题描述】:

我正在处理一个数据集,其中有学生对教师的评分。有些学生不止一次给同一位老师打分。 我想对数据做的是使用以下标准对其进行子集化:

1) 保留所有唯一的学生 ID 和评分

2) 在学生对老师进行两次评分的情况下,只保留 1 个评分,但要随机选择要保留的评分。

3) 如果可能的话,我希望能够在每个分析文件顶部的 munging 脚本中运行代码,并确保为每个分析创建的数据集完全相同(设置种子?)。

# 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)

感谢您就如何前进提供任何指导。

【问题讨论】:

    标签: r


    【解决方案1】:

    假设每个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))
    

    【讨论】:

    • 如果一个学生给多位老师打分会有什么变化?我可以更新我的数据。
    • 拆分必须在与教师和学生 ID 交互的变量上。请参阅我的更新答案。
    • 太棒了。这很有帮助!有没有办法加快该代码?我有 100,000 个 IDS,所以在最终的 do.call 中收敛到一个解决方案是很慢的,或者这是否尽快?
    • 我添加了一个data.table 方法,可以加快速度。
    • 这些太棒了。
    【解决方案2】:

    现在使用data.table 可以更快地完成此操作。您的问题相当于从组内采样行,请参阅

    Sample random rows within each group in a data.table

    【讨论】:

      猜你喜欢
      • 2012-02-05
      • 1970-01-01
      • 1970-01-01
      • 2015-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-24
      • 2019-05-05
      相关资源
      最近更新 更多