In dplyr
, when use pivot_wide
,I want to replace 'NA' at the same time .
Here is the code as below ,they are not work. Anyone can help? Thanks!
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)))
CodePudding user response:
Is this what you want?
test_data %>%
pivot_wider(names_from = 'category',
values_from = 'sales') %>%
unnest(cols = c(A, B)) %>%
mutate(across(where(is.numeric), replace_na, 0))
CodePudding user response:
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