Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change column value by row string value in R

Tags:

r

rename

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.

like image 846
Litwos Avatar asked Nov 23 '14 16:11

Litwos


People also ask

How do I change a specific column value in R?

Method 1: Using Replace() function. replace() function in R Language is used to replace the values in the specified string vector x with indices given in list by those given in values.

How do I replace values in multiple columns in R?

Use R dplyr::coalesce() to replace NA with 0 on multiple dataframe columns by column name and dplyr::mutate_at() method to replace by column name and index. tidyr:replace_na() to replace.


2 Answers

Assuming d is your data.frame:

d$Var2[d$Var1 == "C"] <- "Medium"
like image 98
Thomas Avatar answered Oct 22 '22 19:10

Thomas


try

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

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

like image 27
The_Sound_Maker Avatar answered Oct 22 '22 19:10

The_Sound_Maker