【问题标题】:dcast fun.aggregate=sum in R summing last available column incorrectlydcast fun.aggregate=sum in R 错误地对最后一个可用列求和
【发布时间】:2020-07-25 00:24:15
【问题描述】:

我的数据大致如下:

ID Months Value
1  1       500
1  2       300
1  3       250
1  4       100
2  1       500
2  2       500
2  3       300
3  1       400

我正在尝试将其重新格式化为显示为的短数据格式

ID/Month 1   2    3   4
1        500 300  250 100
2        500 500  300 
3        400

我目前正在使用以下内容:

dcast(data, ID ~ Month, fun.aggregate=sum, value.var="Value")

问题是这错误地对最后一个可用数据点进行了加倍,我的输出如下所示:

ID/Month 1   2    3   4
1        500 300  250 200
2        500 500  600 
3        800

我不确定如何最好地解决或解决此问题。不幸的是,我无法共享任何数据,但是有没有办法绕过“fun.aggregate”组件并让它只列出“值”字段中的数值?我怀疑这是最后一个数据点中双重求和的原因。

不胜感激!

【问题讨论】:

  • 无法使用提供的示例数据重现此情况。
  • @27ϕ9 不幸的是,我根本无法分享实际数据,但这些示例大致只是为了说明问题。我正在下载一个 csv 文件并将其作为数据帧读入。
  • 您需要准备代表您的实际数据的数据。对于共享的数据,我根本不明白您为什么需要fun.aggregate=sum,因为每个值都已被唯一标识。因此,如果您将其从 dcast 中删除,它仍然会提供相同的输出。

标签: r reshape2


【解决方案1】:

数据:

zz <- "ID Months Value
       1  1       500
       1  2       300
       1  3       250
       1  4       100
       2  1       500
       2  2       500
       2  3       300
       3  1       400"

data <- read.table(text=zz, header = TRUE)

使用reshape2 包:

library(reshape2)

代码:

data %>% 
  dcast(ID ~ Months, sum) %>% 
  rename("ID/Month" = "ID")

输出:

ID/Month   1         2          3         4
<int>      <int>     <int>      <int>     <int>
1          500       300        250       100
2          500       500        300       0
3          400       0          0         0

使用tidyverse 包:

library(tidyverse)

代码:

data %>% 
  pivot_wider(names_from = "Months", values_from = "Value")

输出:

#> # A tibble: 3 x 5
#>      ID   `1`   `2`   `3`   `4`
#>   <int> <int> <int> <int> <int>
#> 1     1   500   300   250   100
#> 2     2   500   500   300    NA
#> 3     3   400    NA    NA    NA

reprex package (v0.3.0) 于 2020 年 7 月 24 日创建

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-20
    • 1970-01-01
    • 2015-12-08
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 2013-02-19
    • 1970-01-01
    相关资源
    最近更新 更多