gpt4 book ai didi

r - 对应列为1时如何赋值?

转载 作者:行者123 更新时间:2023-12-05 09:04:21 24 4
gpt4 key购买 nike

Year=c(2001,2001,2001,2001,2001,2001,
2002,2002,2002,2002,2002,2002,
2003,2003,2003,2003,2003,2003)
Factory=c("A","B","C","A","B","C",
"A","B","C","A","B","C",
"A","B","C","A","B","C")
Distribution=c(10023,12034,13948,10294,20494,34549,
28979,34924,29845,18346,47377,65297,
39081,85393,18273,82634,87635,64576,
72368,25764,25863,45786,32789,38297)
Product=c("Cola","Cola","Cola","PepsiCo","PepsiCo","PepsiCo",
"Cola","Cola","Cola","PepsiCo","PepsiCo","PepsiCo",
"Cola","Cola","Cola","PepsiCo","PepsiCo","PepsiCo")

df=data.frame(Year,Factory,Distribution,Product)

这是我通过工厂分离的编码。

df %>%
mutate(Product = 1) %>%
pivot_wider(names_from = Factory,
values_from = Product,
values_fill = list(Product = 0))

enter image description here

Distribution列的值=1时如何分别给A B C赋值,按年份排列?

预期输出如下:

enter image description here

最佳答案

这是一个方法。使用 Product 作为 id 列,并在 reshape 后,将其从结果中删除。

library(dplyr)
library(tidyr)

df %>%
pivot_wider(
names_from = Factory,
values_from = Distribution,
values_fill = list(Distribution = 0)
) %>%
select(-Product)
## A tibble: 6 x 4
# Year A B C
# <dbl> <dbl> <dbl> <dbl>
#1 2001 10023 12034 13948
#2 2001 10294 20494 34549
#3 2002 28979 34924 29845
#4 2002 18346 47377 65297
#5 2003 39081 85393 18273
#6 2003 82634 87635 64576

关于r - 对应列为1时如何赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68806434/

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