使用功能集按行值分组

时间:2019-05-10 05:22:48

标签: r dataframe lapply

嗨,如何将lappy()应用于行中的值?

可以说我的数据集是

Name     value      month
SP        50       January
Mary      67       January
Justin    33       January

SP        45       February
Mary      37       February
Justin    53       February

SP        55       March
Mary      67       March
Justin    23       March

因此,如果我需要查找每个月的值之和, 将我的内容发布为:

Month        Value
January       150
February      135
March         145

目前,我只知道如何在没有每月间隔的情况下总体上计算此值:

library(tidyverse)
x <- tibble(Name = c("SP","Mary","Justin","SP","Mary","Justin","SP","Mary","Justin"),
            value = c(50,67,33,45,37,53,55,67,23),
            Month = c("January", "January", "February", "February","March","March"))
y <- data.frame(x,sum(x$value))

我不知道如何获得理想的结果。 知道如何吗?

1 个答案:

答案 0 :(得分:-2)

我们可以使用aggregate中的base R

aggregate(value ~ Month, x, sum)

或与dplyr

library(dplyr)
x %>%
   group_by(Month) %>%
   summarise(value = sum(value))