gpt4 book ai didi

r - 然后根据 R 中返回的新值匹配两列中的值

转载 作者:行者123 更新时间:2023-12-01 13:57:23 25 4
gpt4 key购买 nike

我在数据框中有这些列,如下所示:

combination  color_1  color_2

1_1 red red
1_2 red blue
1_3 red green
1_4 red yellow
2_1 blue red
2_2 blue blue
2_3 blue green
2_4 blue yellow
...

基于匹配 color_1 和 color_2 值,我希望能够创建输出匹配结果的新列。 对此有一定的规范。对于“red”和“red”相同的第一行,新列中的输出(例如“Red-Only”)应该是“1” ,然后每隔一个匹配项为“2”。然后,我会重复这段代码,然后选择出现“blue”和“blue”的匹配项,在下一列(例如“Blue-Only”)中输出“1”,在其他任何地方输出“2”。这适用于仅限黄色的比赛、仅限绿色的比赛等。所以最后我会根据条件有 4 个额外的列。

提前感谢您的帮助!

最佳答案

让我们从您现有的数据开始:

df <- structure(list(combination = c("1_1", "1_2", "1_3", "1_4", "2_1", 
"2_2", "2_3", "2_4"), color_1 = c("red", "red", "red", "red",
"blue", "blue", "blue", "blue"), color_2 = c("red", "blue", "green",
"yellow", "red", "blue", "green", "yellow")), class = "data.frame", row.names = c(NA,
-8L))

combination color_1 color_2
1 1_1 red red
2 1_2 red blue
3 1_3 red green
4 1_4 red yellow
5 2_1 blue red
6 2_2 blue blue
7 2_3 blue green
8 2_4 blue yellow

一种解决方案是遍历四种颜色类别,检查是否匹配。

colors <- c('red', 'green', 'yellow', 'blue')

matches <- lapply(colors, function(x) {
out <- ifelse(with(df, color_1 == color_2 & color_1 == x), 1, 2)
out
})

然后用您想要的列名称命名此操作的结果。

names(matches) <- paste(colors, 'only', sep = '_')

最后,将结果与原始数据粘合在一起:

df.new <- cbind(df, as.data.frame(matches))

combination color_1 color_2 red_only green_only yellow_only blue_only
1 1_1 red red 1 2 2 2
2 1_2 red blue 2 2 2 2
3 1_3 red green 2 2 2 2
4 1_4 red yellow 2 2 2 2
5 2_1 blue red 2 2 2 2
6 2_2 blue blue 2 2 2 1
7 2_3 blue green 2 2 2 2
8 2_4 blue yellow 2 2 2 2

关于r - 然后根据 R 中返回的新值匹配两列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58596926/

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