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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With