如何按组减少此数据框?

时间:2016-11-11 13:53:47

标签: r reduce

我有以下

t <- structure(list(name = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L), .Label = c("Alice", "Bob",
"Jane Doe", "John Doe"), class = "factor"), school = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L), .Label = c("Alice School",
"Bob School", "Someother School", "Someschool College"), class = "factor"),
    group = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("A", "B"), class = "factor"),
    question = structure(c(2L, 4L, 6L, 8L, 1L, 3L, 5L, 7L, 2L,
    4L, 6L, 8L, 1L, 3L, 5L, 7L, 2L, 4L, 6L, 8L, 1L, 3L, 5L, 7L,
    2L, 4L, 6L, 8L, 1L, 3L, 5L, 7L), .Label = c("q1", "q2", "q3",
    "q4", "q5", "q6", "q7", "q8"), class = "factor"), mark = c(0L,
    0L, 0L, 0L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L,
    1L, 1L, 0L, 1L, 0L, 1L, 0L, 1L, 0L, 1L, 1L, 0L, 1L, 0L, 1L,
    1L), subject = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
    1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
    2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), .Label = c("C", "M"), class = "factor")), .Names = c("name",
"school", "group", "question", "mark", "subject"), row.names = c(7L,
15L, 23L, 31L, 3L, 11L, 19L, 27L, 8L, 16L, 24L, 32L, 4L, 12L,
20L, 28L, 6L, 14L, 22L, 30L, 2L, 10L, 18L, 26L, 5L, 13L, 21L,
29L, 1L, 9L, 17L, 25L), class = "data.frame")

我需要制作一个数据框,其中每个学生每个科目都有一个组合标记。该组合只是每个问题上的标记的总和。因此,例如,Jane Doe将有3个主题C和2个主题M.我已经用Reduce和其他方法敲了很长时间。我可以用一种非常程序化的方式来解决这个问题,但如果我能用一行(或近似)来解决这个问题,我会更开心。我确定可以做到......

3 个答案:

答案 0 :(得分:5)

你在问题​​中这么说;你想要group_by学生和科目并计算总和

library(tidyverse)
asdf %>%
  group_by(name, subject) %>%
  summarise(score = sum(mark))

答案 1 :(得分:4)

这是一个data.table解决方案:

library(data.table)
setDT(t)[, sum(mark), by = list(name, subject)]

答案 2 :(得分:3)

只是为了完整性,基础R:

aggregate(mark ~ name + subject, data=t, sum)

这表示“使用mark作为聚合函数”,通过分组变量namesubject汇总响应变量sum