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)))