我确信这很简单,但我无法让它工作
我需要将两个值相加,而其他列使用reshape / melt保持不变:
数据看起来像这样:
ID Value
1 2850508 1010.58828
2 2850508 94.37286
期望的输出:
ID Variable Value
1 2850508 Cost 1104.96114
当前输出:
ID Variable Value
1 2850508 Cost 1010.58828
2 2850508 Cost 94.37286
当前代码:
Sum <- melt(Data, id="ID", measured="Cost")
任何帮助将不胜感激!
答案 0 :(得分:2)
使用dplyr
:(我添加了两个ID,以便有更多数据):
d
是您的数据
d %>%
group_by(ID) %>%
summarise(Value=sum(Value)) %>%
mutate(Variable="Cost") %>%
select(ID,Variable,Value)
ID Variable Value
1 2850508 Cost 1104.961
2 2850509 Cost 1164.961
3 2850510 Cost 1047.961
答案 1 :(得分:2)
您也可以使用aggregate
功能。
aggregate(formula = . ~ ID,
data = Data ,
FUN = sum)
## ID Value
## 1 2850508 1104.961
要获得所需的输出,您必须cbind
并重新排列:
cbind(aggregate(formula = . ~ ID,
data = Data ,
FUN = sum),
Variable = "Cost")[, c("ID", "Variable", "Value")]
答案 2 :(得分:1)
data.table
library(data.table)
setDT(df)[, .(Variable = "Cost", Value = sum(Value)) , ID]
# ID Variable Value
# 1: 2850508 Cost 1104.961