1

My question is similar to another one: R replace specific value in many columns across dataframe

However I need to replace values based on a vector from another column rather than with NA or a constant.

Can you please help?

#there are many more yrs in the data set
yr1<-c("1","missing")
yr2<-c("3","4")
right<-c("2","3")
df<-data.frame(yr1,yr2,right)

df<-df %>%
  mutate(
      across(starts_with('yr'), ~replace(.x, ~.x=="missing", right) ))

Where right is another column where I want to "lookup" the value to replace the "missing" value.

2 Answers 2

2

Using ifelse instead of replace should solve your problem.

library(dplyr)

df %>%
  mutate(across(starts_with('yr'), ~ifelse(.x=="missing", right, .x)))

#  yr1 yr2 right
#1   1   3     2
#2   3   4     3

In general, I would suggest to use replace only when you have a fixed (constant) value to replace for all other things using ifelse is better.

Sign up to request clarification or add additional context in comments.

2 Comments

Actually I have a followup question, if I need to mutate but based on a condition on another column, what do I need instead of other.column? @Ronak Shah Something like df %>% mutate(across(starts_with('yr'), ~ifelse(other.column=="C", right, .x)))
@melange164 Exactly, that should work if other.column is the name of the column.
0

base R option:

cols <- grep("^yr\\d+$", names(df))
df[cols][df[cols] == "missing"] <- df[df[cols] == "missing", "right"]

Output:

  yr1 yr2 right
1   1   3     2
2   3   4     3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.