Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 558
Daniel Avatar asked May 08 '18 16:05

Daniel


1 Answers

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))
like image 82
akrun Avatar answered Oct 24 '22 20:10

akrun