我有以下数据框:
Event Scenario Year Cost
1 1 1 10
2 1 1 5
3 1 2 6
4 1 2 6
5 2 1 15
6 2 1 12
7 2 2 10
8 2 2 5
9 3 1 4
10 3 1 5
11 3 2 6
12 3 2 5
我需要制作一个数据透视表/框架,它将每个方案的每年总费用相加。结果将是。
Scenario Year Cost
1 1 15
1 2 12
2 1 27
2 2 15
3 1 9
3 2 11
我需要制作一个ggplot折线图,用于绘制每年每个方案的成本。我知道怎么做,我只是无法获得正确的数据框。
答案 0 :(得分:4)
尝试
library(dplyr)
df %>% group_by(Scenario, Year) %>% summarise(Cost=sum(Cost))
或者
library(data.table)
setDT(df)[, list(Cost=sum(Cost)), by=list(Scenario, Year)]
或者
aggregate(Cost~Scenario+Year, df,sum)
df <- structure(list(Event = 1:12, Scenario = c(1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 3L, 3L, 3L, 3L), Year = c(1L, 1L, 2L, 2L, 1L, 1L,
2L, 2L, 1L, 1L, 2L, 2L), Cost = c(10L, 5L, 6L, 6L, 15L, 12L,
10L, 5L, 4L, 5L, 6L, 5L)), .Names = c("Event", "Scenario", "Year",
"Cost"), class = "data.frame", row.names = c(NA, -12L))
答案 1 :(得分:0)
以下是:
library(plyr)
ddply(df, .(Scenario, Year), summarize, Cost = sum(Cost))
#Scenario Year Cost
#1 1 1 15
#2 1 2 12
#3 2 1 27
#4 2 2 15
#5 3 1 9
#6 3 2 11