在`dplyr`中,当使用`pivot_wide`时,我想同时替换'NA'
In `dplyr`, when use `pivot_wide` ,I want to replace 'NA' at the same time
在dplyr
中,使用pivot_wide
时,我想同时替换'NA'。
这是下面的代码,它们不起作用。任何人都可以帮忙吗?谢谢!
library(tidyverse)
test_data <- data.frame(category=c('A','B','A','B','A','B','A','B'),
sub_category=c('a1','b1','a2','b2','a1','b1','a2','b2'),
sales=c(1,2,4,5,8,1,4,6))
#method1: Error: Can't convert <double> to <list>.
test_data %>% pivot_wider(names_from = 'category',
values_from = 'sales',
values_fill = 0) %>% unnest()
#method2: code can't run
test_data %>% pivot_wider(names_from = 'category',
values_from = 'sales') %>% unnest() %>%
as.data.frame() %>%
mutate(across(where(is.numeric),function(x) stringr::str_replace('NA',0)))
这是你想要的吗?
test_data %>%
pivot_wider(names_from = 'category',
values_from = 'sales') %>%
unnest(cols = c(A, B)) %>%
mutate(across(where(is.numeric), replace_na, 0))
test_data %>%
pivot_wider(names_from = 'category', values_from = 'sales',
values_fn = list, values_fill = list(0)) %>%
unnest(c(A, B))
# A tibble: 8 x 3
sub_category A B
<chr> <dbl> <dbl>
1 a1 1 0
2 a1 8 0
3 b1 0 2
4 b1 0 1
5 a2 4 0
6 a2 4 0
7 b2 0 5
8 b2 0 6
在dplyr
中,使用pivot_wide
时,我想同时替换'NA'。
这是下面的代码,它们不起作用。任何人都可以帮忙吗?谢谢!
library(tidyverse)
test_data <- data.frame(category=c('A','B','A','B','A','B','A','B'),
sub_category=c('a1','b1','a2','b2','a1','b1','a2','b2'),
sales=c(1,2,4,5,8,1,4,6))
#method1: Error: Can't convert <double> to <list>.
test_data %>% pivot_wider(names_from = 'category',
values_from = 'sales',
values_fill = 0) %>% unnest()
#method2: code can't run
test_data %>% pivot_wider(names_from = 'category',
values_from = 'sales') %>% unnest() %>%
as.data.frame() %>%
mutate(across(where(is.numeric),function(x) stringr::str_replace('NA',0)))
这是你想要的吗?
test_data %>%
pivot_wider(names_from = 'category',
values_from = 'sales') %>%
unnest(cols = c(A, B)) %>%
mutate(across(where(is.numeric), replace_na, 0))
test_data %>%
pivot_wider(names_from = 'category', values_from = 'sales',
values_fn = list, values_fill = list(0)) %>%
unnest(c(A, B))
# A tibble: 8 x 3
sub_category A B
<chr> <dbl> <dbl>
1 a1 1 0
2 a1 8 0
3 b1 0 2
4 b1 0 1
5 a2 4 0
6 a2 4 0
7 b2 0 5
8 b2 0 6