gpt4 book ai didi

r - 使用 dplyr 有条件地将一列中的值替换为另一列中的值

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

我想将一列中与特定条件匹配的值替换为同一行中不同列中的值。考虑这个例子:

library(tidyverse)
data <- tribble(
~X25, ~Other,
"a", NA,
"b", NA,
"Other", "c",
"Other", "d"
)
View(data)

# Works to change values in X25
within(data, {
X25 <- ifelse(X25 == "Other", Other, X25)
})

# Changes values in X25 to NA and doesn't replace X25 with appropriate value from Other column
data %>% mutate(X25 = replace(X25, X25 == "Other", Other))

使用“within”的代码效果很好。如果需要,我如何使用 dplyr(作为较长的变异/总结过程的一部分)?

编辑:这是与 Change value of variable with dplyr 不同的场景。我不想盲目地为所有匹配的单元格分配相同的值(例如 NA)。我想从另一个特定的列中提取它们。

最佳答案

使用replace,长度应该相同,因此我们需要使用逻辑表达式对Other进行子集化

data %>%
mutate(X25 = replace(X25, X25 == "Other", Other[X25=="Other"]))
<小时/>

另一个选项是case_when

data %>%
mutate(X25 = case_when(X25=="Other"~ Other,
TRUE ~ X25))

或者如果否则

data %>%
mutate(X25 = ifelse(X25 == "Other", Other, X25))

关于r - 使用 dplyr 有条件地将一列中的值替换为另一列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50238151/

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