gpt4 book ai didi

r - Pivot_wider/spread 而不是 value_from 或值只是 1?

转载 作者:行者123 更新时间:2023-12-04 11:00:46 25 4
gpt4 key购买 nike

如果真/假,我想采用一个功能并将其值作为带有 1/0 的列进行传播,例如

mtcars %>% 
pivot_wider(names_from = cyl,
values_from = 1)

这似乎已经做了一些事情,cyl 现在已经扩展到列中,除了值是 21、21.4 或 NA 之类的东西。
> mtcars %>% 
+ pivot_wider(names_from = cyl,
+ values_from = 1)
# A tibble: 32 x 12
disp hp drat wt qsec vs am gear carb `6` `4` `8`
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 160 110 3.9 2.62 16.5 0 1 4 4 21 NA NA
2 160 110 3.9 2.88 17.0 0 1 4 4 21 NA NA
3 108 93 3.85 2.32 18.6 1 1 4 1 NA 22.8 NA
4 258 110 3.08 3.22 19.4 1 0 3 1 21.4 NA NA
5 360 175 3.15 3.44 17.0 0 0 3 2 NA NA 18.7
6 225 105 2.76 3.46 20.2 1 0 3 1 18.1 NA NA
7 360 245 3.21 3.57 15.8 0 0 3 4 NA NA 14.3
8 147. 62 3.69 3.19 20 1 0 4 2 NA 24.4 NA
9 141. 95 3.92 3.15 22.9 1 0 4 2 NA 22.8 NA
10 168. 123 3.92 3.44 18.3 1 0 4 4 19.2 NA NA

我尝试使用 values_fill像这样:
> mtcars %>% 
+ pivot_wider(names_from = cyl,
+ values_from = 1,
+ values_fill = list(1 = 0))
Error: unexpected '=' in:
" values_from = 1,
values_fill = list(1 ="

如何根据 cyl 是 4、6 还是 8 将 cyl 分布在具有二进制 1 或 0 值的列中?

pivot_wider() 是我想要的吗?

最佳答案

套装mpg为 1 并为 mpg 设置填充到 0 像这样:

mtcars %>%
mutate(mpg = 1) %>%
pivot_wider(names_from = cyl, values_from = mpg, values_fill = list(mpg = 0))
## # A tibble: 32 x 12
## disp hp drat wt qsec vs am gear carb `6` `4` `8`
## <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 160 110 3.9 2.62 16.5 0 1 4 4 1 0 0
## 2 160 110 3.9 2.88 17.0 0 1 4 4 1 0 0
## 3 108 93 3.85 2.32 18.6 1 1 4 1 0 1 0
## ... etc ...

或给出 pivot_wider 的问题目前有订购列,您可能更喜欢旧的 spread :
mtcars %>%
mutate(mpg = 1) %>%
spread(cyl, mpg, fill = 0)
## disp hp drat wt qsec vs am gear carb 4 6 8
## 1 71.1 65 4.22 1.835 19.90 1 1 4 1 1 0 0
## 2 75.7 52 4.93 1.615 18.52 1 1 4 2 1 0 0
## 3 78.7 66 4.08 2.200 19.47 1 1 4 1 1 0 0
## ... etc ...

或者像这样指定 values_fn :
mtcars %>%
pivot_wider(names_from = cyl, values_from = mpg,
values_fn = list(mpg = ~ 1), values_fill = list(mpg = 0))
## # A tibble: 32 x 12
## disp hp drat wt qsec vs am gear carb `6` `4` `8`
## <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 160 110 3.9 2.62 16.5 0 1 4 4 1 0 0
## 2 160 110 3.9 2.88 17.0 0 1 4 4 1 0 0
## 3 108 93 3.85 2.32 18.6 1 1 4 1 0 1 0
## ...etc...

关于r - Pivot_wider/spread 而不是 value_from 或值只是 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58809885/

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