Update a Value in One Column Based on Criteria in Other Columns
r
Solution
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'
})
Problem
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" ```