11

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.

Daniel
  • 365
  • 1
  • 4
  • 13

1 Answers1

15

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))
akrun
  • 674,427
  • 24
  • 381
  • 486
  • 1
    @stevec yes, you are right. In general, it would be better to convert `factor` to `character` before doing the. conversion or use `ifelse(as.character(X25) == "Other", as.character(Other), as.character(X25)))` or else have to add `levels` (if there are some new levels) before the conversion in `case_when` etc – akrun Mar 15 '20 at 02:54