在 tidyr::pivot_wider 中,`values_fn = sum(.,na.rm=TRUE)` 失败
In tidyr::pivot_wider, `values_fn = sum(.,na.rm=TRUE)` failed
在tidyr::pivot_wider中,values_fn = sum(.,na.rm=TRUE)
失败,如何处理?
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))
你可以让它成为一个函数来处理这个:
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
创建匿名函数的新语法 (\(x)
) 也适用:
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
由 reprex package (v2.0.1)
于 2022-03-25 创建
在tidyr::pivot_wider中,values_fn = sum(.,na.rm=TRUE)
失败,如何处理?
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))
你可以让它成为一个函数来处理这个:
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
创建匿名函数的新语法 (\(x)
) 也适用:
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
由 reprex package (v2.0.1)
于 2022-03-25 创建