Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update a Value in One Column Based on Criteria in Other Columns

Tags:

r

If my data frame (df) looks like this:

Name        State John Smith  MI John Smith  WI Jeff Smith  WI 

I want to rename the John Smith from WI "John Smith1". What is the cleanest R equivalent of the SQL statement?

update df  set Name = "John Smith1" where Name = "John Smith" and State = "WI" 
like image 670
Frank B. Avatar asked Feb 21 '15 20:02

Frank B.


People also ask

How do I change the value of a column based on another column?

In such a case, you can use the following UPDATE statement syntax to update column from one table, based on value of another table. UPDATE first_table, second_table SET first_table. column1 = second_table. column2 WHERE first_table.id = second_table.

How can I obtain a value in one column based on another column in Excel?

Combining INDEX and MATCH to Lookup Value in Column and Return Value of Another Column. Apart from that, you can use nested INDEX and MATCH formulas to lookup for a value in a column and get the result of another column in the dataset.

How can I update a column from one table to another in SQL?

UPDATE syntax: UPDATE table_name SET column_name = value WHERE condition; To perform the above function, we can set the column name to be equal to the data present in the other table, and in the condition of the WHERE clause, we can match the ID.


2 Answers

df <- data.frame(Name=c('John Smith', 'John Smith', 'Jeff Smith'),                  State=c('MI','WI','WI'), stringsAsFactors=F)  df <- within(df, Name[Name == 'John Smith' & State == 'WI'] <- 'John Smith1')  > df          Name State 1  John Smith    MI 2 John Smith1    WI 3  Jeff Smith    WI 

** Edit **

Edited to add that you can put whatever you like in the within expression:

df <- within(df, {     f <- Name == 'John Smith' & State == 'WI'     Name[f] <- 'John Smith1'     State[f] <- 'CA' })  
like image 72
Zelazny7 Avatar answered Oct 11 '22 19:10

Zelazny7


One way:

df[df$Name == "John_Smith" & df$State == "WI", "Name"] <- "John_Smith1" 

Another way using the dplyr:

df %>% mutate(Name = ifelse(State == "WI" & Name == "John_Smith", "John_Smith1", Name)) 

Note: As David Arenburg says, the first column should not be a factor. For this, reading the data set stringsAsFactors = FALSE.

like image 24
DatamineR Avatar answered Oct 11 '22 20:10

DatamineR