0

所以这个数据框有很多单独的观察,我需要将它们加在一起。

使用 dget():

我尝试了很多不同的解决方案,例如:

df %>% 
  group_by(product, price) %>% 
  summarise(
    quantity = sum(quantity),
    total = sum(total)
  )

和:

df %>%
  gather(key = variable, value = value, c(Quantity,Price,Total)) %>%
  group_by(Product, variable) %>%
  summarize(sum = sum(value)) %>%
  spread(variable, sum)

和:

df %>%
          group_by(Product) %>%
          summarise(Quantity = sum(Quantity),
          AveragePrice = sum(Total)/sum(Quantity),
          Total = sum(Total))

但我只是得到:

> df
  quantity total
1       61  1685

预期的输出是这样的,但显然product列中的所有产品:

#> # Groups:   product [2]
#>   product        price quantity total
#>   <chr>          <dbl>    <dbl> <dbl>
#> 1 small cucumber    10        1    10
#> 2 tomatoes 1kg      16        2    32

我以前问过这个,但我还不够具体。

谢谢。

4

1 回答 1

0

你打电话plyr::summarise而不是dplyr::summarise. 您可以使用显式调用它

df %>%
  group_by(Product) %>%
  dplyr::summarise(
    Quantity = sum(Quantity),
    AveragePrice = sum(Total)/sum(Quantity),
    Total = sum(Total))
#> # A tibble: 27 x 4
#>    Product                      Quantity AveragePrice Total
#>    <chr>                           <dbl>        <dbl> <dbl>
#>  1 asparagus 200g                      4           45   180
#>  2 back bacon 200g                     1           30    30
#>  3 beef fillet strips 500g             1           90    90
#>  4 beetroot 1kg                        1           15    15
#>  5 broccoli head                       1           25    25
#>  6 butter 500g                         1           57    57
#>  7 butternut cubes                     4           14    56
#>  8 calistos jalape=c3=b1o salsa        1           40    40
#>  9 carrot 1 kg                         4           14    56
#> 10 cauliflower whole head              2           25    50
#> # … with 17 more rows
于 2020-11-13T15:16:17.190 回答