'In tidyr::pivot_wider, `values_fn = sum(.,na.rm=TRUE)` failed

In tidyr::pivot_wider, values_fn = sum(.,na.rm=TRUE) failed ,how to handle it?

library(tidyverse)
test_data <- data.frame(
  category=c('A','A','A','B','B','B'),
  sub_category=c('a','b','b','a','b','b'),
  amount=1:6
)

test_data %>% pivot_wider(names_from ='category',
                          values_from ='amount' ,
                          values_fn = sum(.,na.rm=TRUE)) 


Solution 1:[1]

You can make it a function to handle this:

library(tidyverse)
test_data <- data.frame(
  category=c('A','A','A','B','B','B'),
  sub_category=c('a','b','b','a','b','b'),
  amount=1:6
)

test_data %>% pivot_wider(names_from ='category',
                          values_from ='amount' ,
                          values_fn = function(x) sum(x, na.rm = TRUE))

#> # A tibble: 2 x 3
#>   sub_category     A     B
#>   <chr>        <int> <int>
#> 1 a                1     4
#> 2 b                5    11

The new syntax for making an anonymous function (\(x)) works too:

test_data %>% pivot_wider(names_from ='category',
                          values_from ='amount' ,
                          values_fn = \(x) sum(x, na.rm = TRUE))

#> # A tibble: 2 x 3
#>   sub_category     A     B
#>   <chr>        <int> <int>
#> 1 a                1     4
#> 2 b                5    11

Created on 2022-03-25 by the reprex package (v2.0.1)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andy Baxter