【问题标题】:Tabulating school grades with data.table (long form to wide form)用 data.table 对学校成绩进行制表(长格式到宽格式)
【发布时间】:2017-02-13 07:30:58
【问题描述】:

我有大量的课程数据库,其中包含年级和学生 ID。它看起来像这样(为了简化而删除了更多变量):

studentID    course       grade
--------------------------------
1            chemistry    86
2            chemistry    85
2            math         72
3            english      52
3            math         90
...

我需要将该大文件转换为一个文件,其中每个学生都有自己的行,其中包含所有不同课程的成绩。更像这样的东西:

studentID    chemistry    math    english
----------------------------------------
1            86           NA      NA
2            85           72      NA
3            NA           90      52

这是创建我的采样器数据库的代码:

course.db <- data.table(
              studentID=c("1", "2", "2", "3", "3"),
              course=c("chemistry", "chemistry", "math", "english", "math"),
              grade=c(86, 85, 72, 52, 90)
           )

我通常做的是使用通常的信息(GPA、学校等)创建一个学生文件数据库,如下所示:

student.files <- course.db[, .(
    average=mean(grade, na.rm=T) #more vars are created here
), by="studentID"]

然后我用我需要的成绩创建另一个表:

math.grades <- course.db[course=="math", .(
    math=grade
), by="studentID"]

然后我合并整个事情。当只有几门课程可以从中获得成绩时,这很有效。但我需要从至少十几门课程中汇总成绩。所以我的问题是:我如何根据“等级”列的值有条件地评估等级?我在寻找什么:

#careful: not working code
student.files <- course.db[, .(
    average = mean(grade, na.rm=T) #more vars are created here,
    math = ThenAMiracleOccurs("math", grade),
    english = ThenAMiracleOccurs("english", grade),
    chemistry = ThenAMiracleOccurs("chemistry", grade),
), by="studentID"]

【问题讨论】:

    标签: r data.table


    【解决方案1】:

    谢谢休伯特。我没有注意到有一个 data.table 版本(我的数据库很大,所以我需要尽可能留在 data.table 世界中)。这是一个使用 dcast for data.table 的工作解决方案:

    dcast.data.table(course.db, studentID~course, value.var="grade" )
    

    注释中指出:只要表已经是 data.table 对象,简单的 dcast 也可以使用并使用 data.table 方法:

    dcast(course.db, studentID~course, value.var="grade" )
    

    结果:

       studentID chemistry english math
    1:         1        86      NA   NA
    2:         2        85      NA   72
    3:         3        NA      52   90
    

    【讨论】:

    • 最新版本的data.table不需要调用dcast.data.table,只要course.db已经是data.table,就可以直接使用dcast
    猜你喜欢
    • 2020-07-01
    • 2021-09-18
    • 1970-01-01
    • 2020-11-20
    • 1970-01-01
    • 2019-02-13
    • 2021-02-08
    • 2011-01-27
    • 2021-08-01
    相关资源
    最近更新 更多