Conditionally replace values in one column with values from another column using dplyr [duplicate]

流过昼夜 提交于 2021-01-21 07:12:18

问题


I want to replace the values in one column that match a certain condition with values in that same row from a different column. Consider this example:

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))

The code using "within" works well. How can I use dplyr if needed (as part of a longer mutate / summarise process)?

Edit: This is a different scenario from Change value of variable with dplyr. I don't want to blindly assign all matching cells with the same value (e.g., NA). I wanted to pull them from another particular column.


回答1:


With replace, the lengths should be the same, so we need to subset the Other as well with the logical expression

data %>%
    mutate(X25 = replace(X25, X25 == "Other", Other[X25=="Other"]))

Another option would be case_when

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

Or ifelse

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


来源:https://stackoverflow.com/questions/50238151/conditionally-replace-values-in-one-column-with-values-from-another-column-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!