R Reshape - 求和与合并

R Reshape - Sum and Combine

我相信这真的很简单,但我无法让它工作

我需要对两个值求和,而其他列使用 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")

如有任何帮助,我们将不胜感激!

使用 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

您也可以只使用 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")]

data.table

也很简单
library(data.table)
setDT(df)[, .(Variable = "Cost", Value = sum(Value)) , ID]
#         ID Variable    Value
# 1: 2850508     Cost 1104.961