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))
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With