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

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.


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'
}) 

You can also use package data.table:

library(data.table)
setDT(df)[State=="WI", Name:=paste0(Name,"1")]

Tags:

R