首页 > 解决方案 > 在R中对名称旁边的行求和

问题描述

我正在从事一个银行项目,我试图找到每年花费的金额,而数据集将这些列为每月交易。

Month     Name                  Money Spent
  2      John Smith                   10
  3      John Smith                   25
  4      John Smith                   20
  2      Joe Nais                     10
  3      Joe Nais                     25
  4      Joe Nais                     20

现在,这是我的代码:

OTData <- OTData %>%
mutate(
    OTData,
    Full Year = [CODE NEEDED TO SUM UP]
)

谢谢!

标签: r

解决方案


正如@Pawel 所说,这里没有问题。我假设你想要:

df <- data.frame(Month = c(2,3,4,2,3,4),
                 Name = c("John Smith", "John Smith", "John Smith",
                          "Joe Nais", "Joe Nais", "Joe Nais"),
                 Money_Spent = c(10,25,20,10,25,20))
df %>%
    group_by(Name) %>%
    summarize(Full_year = sum(Money_Spent))

  Name       Full_year
  <fct>          <dbl>
1 Joe Nais          55
2 John Smith        55

注意:如果在变量名中包含空格,将会遇到麻烦。您确实应该将它们替换为., _, 或camelCase如上例所示。


推荐阅读