Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading