gpt4 book ai didi

r - 为给定行中的每个唯一值添加列

转载 作者:行者123 更新时间:2023-12-05 08:46:33 24 4
gpt4 key购买 nike

我正在尝试将我当前数据集的格式更改为每行 1 个用户的格式,并将颜色和食物列中的所有唯一值(值的动态数量)拆分为它们自己的列,带有 Yes 和没有。每个用户都有一个唯一的 ID。

Current format: 
ID | Name | Color | Food
1 | John | Blue | Pizza
1 | John | Red | Pizza
1 | John | Yellow | Pizza
1 | John | Blue | Ice Cream
1 | John | Red | Ice Cream
1 | John | Yellow | Ice Cream
2 | Kelly | Blue | Pizza
2 | Kelly | Red | Pizza


Desired format:
ID | Name | Color_Blue | Color_Red | Color_Yellow | Food_Pizza | Food_Ice Cream |
1 | John | Yes | Yes | Yes | Yes | Yes |
2 | Kelly | Yes | Yes | No | Yes | No |

最佳答案

library(dplyr); library(tidyr)
df %>%
pivot_longer(-c(ID:Name)) %>%
unite("col", c(name, value)) %>%
distinct(ID, Name, col) %>%
mutate(val = "Yes") %>%
pivot_wider(names_from = col, values_from = "val", values_fill = "No")

# A tibble: 2 x 7
ID Name Color_Blue Food_Pizza Color_Red Color_Yellow `Food_Ice Cream`
<chr> <chr> <chr> <chr> <chr> <chr> <chr>
1 1 John Yes Yes Yes Yes Yes
2 2 Kelly Yes Yes Yes No No

如果您想要一个基本的 R 等价物,这里有一个使用相同步骤的。 (有人可以帮我弄清楚如何删除行名和附加到最终列名的“val.”吗?)

df2 <- reshape(df, 
direction = "long",
varying = c("Color", "Food"),
v.names = "Value",
timevar = "col_name",
times = c("Color", "Food"))
df2$col = paste(df2$col_name, df2$Value, sep = "_")

df3 <- unique(df2[c("ID", "Name", "col")])
df3$val = "Yes"

df4 <- reshape(df3,
direction = "wide",
idvar = c("ID", "Name"),
timevar = "col")
df4[is.na(df4)] <- "No"

> df4
ID Name val.Color_Blue val.Color_Red val.Color_Yellow val.Food_Pizza val.Food_Ice Cream
1.Color 1 John Yes Yes Yes Yes Yes
7.Color 2 Kelly Yes Yes No Yes No

样本数据

df <- tribble(~ID , ~Name  , ~Color  , ~Food,
"1" , "John", "Blue", "Pizza",
"1" , "John" , "Red", "Pizza",
"1" , "John", "Yellow", "Pizza",
"1" , "John" , "Blue", "Ice Cream",
"1" , "John", "Red", "Ice Cream",
"1" , "John" , "Yellow", "Ice Cream",
"2" , "Kelly", "Blue", "Pizza",
"2" , "Kelly", "Red", "Pizza")

关于r - 为给定行中的每个唯一值添加列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69536702/

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