user3027387
user3027387

Reputation: 13

R replace values in one column upon matching conditions in another column

I am having trouble finding a solution to this: I want to replace those NA values with some text depending on the name of the variable. Ideally it would do something like:

if variable name is var2 or var3 or var4 replace in the same row with "text"

               variable question
1               var1     <NA>
2               var2     <NA>
3               var3     <NA>
4               var4     <NA>

The closest I thought would work was:

df$question[df$variable = var2 OR var3 OR var4] <- text

it shouldn't be hard, i am just to blind to find the right answers :(.

Upvotes: 1

Views: 5342

Answers (1)

Jilber Urbina
Jilber Urbina

Reputation: 61214

If text is the same for var2, var3, var4 then, this should do the trick. Otherwise, if text is different for each var*, then update your question and provide us with more details.

> df$question <- as.character(df$question)
> df$question[df$variable %in% c("var2", "var3", "var4")] <- "text"
> df
  variable question
1     var1     <NA>
2     var2     text
3     var3     text
4     var4     text

Upvotes: 4

Related Questions