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.

user438383
  • 5,716
  • 8
  • 28
  • 43
melange164
  • 143
  • 6

2 Answers2

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.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • 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 May 19 '22 at 11:53
  • @melange164 Exactly, that should work if `other.column` is the name of the column. – Ronak Shah May 19 '22 at 13:40
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
Quinten
  • 35,235
  • 5
  • 20
  • 53