Litwos
Litwos

Reputation: 1338

Change column value by row string value in R

I'm having a problem with a set of data. I want to change the values of a column, only for certain values in the rows of data. My table has this structure:

  Var1   Var2
1   A    High
2   A    High
3   A    High
4   B    High
5   B    High
6   B    High
7   C    High
8   C    Low
9   C    Low
10  C    Low

Now, I want to change the "Var2" values to "Medium", only when Var 1 is C. Thank you for help! :) Alin.

Upvotes: 7

Views: 27019

Answers (2)

The_Sound_Maker
The_Sound_Maker

Reputation: 11

try

d$Var2[d$Var1 == "C", ] <- "Medium"

There has to be a comma after the condition. This is a R-specific thing.

Upvotes: 1

Thomas
Thomas

Reputation: 44555

Assuming d is your data.frame:

d$Var2[d$Var1 == "C"] <- "Medium"

Upvotes: 8

Related Questions