gpt4 book ai didi

r - 在 `dplyr` 中,当使用 `pivot_wide` 时,我想同时替换 'NA'

转载 作者:行者123 更新时间:2023-12-02 16:02:27 24 4
gpt4 key购买 nike

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',
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

关于r - 在 `dplyr` 中,当使用 `pivot_wide` 时,我想同时替换 'NA',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70269158/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com