r 按国家和部门分类的总值

r aggregate value by country and department

我有一个包含 200 个国家、部门和成本的大型数据集。

70 000 行 -(国家和部门在数据集中超过 1 次)

我的目标是获得如下所示的数据框:

target output

假设您的数据位于名为 df...

的数据框中
library(dplyr)
library(tidyr)
df %>%
  group_by(country, department) %>%
  summarise(costs = sum(costs)) %>%
  spread(department, costs)

阅读更多关于 dplyr, tidyr and the tidyverse 的信息,它们会让您的生活变得 很多 轻松。