Reputation: 11584
I have a large dataframe. I need to update a particular variable as illustrated in below reproducible code:
df <- data.frame(source = c('mercury','inbound','leaflet','local','campaigning','branding'),
amount = c(100,99,101,87,123,99))
I need something equivalent of below SQL code in R.
update df set source = 'ABC' where source in ('leaflet','local','campaigning','branding')
I can make do with gsub but I can update based on only one condition at a time, but I need to update multiple values based on multiple conditions as above.
Upvotes: 0
Views: 103
Reputation: 887158
We can use case_when
from dplyr
library(dplyr)
df %>%
mutate(source = case_when(source %in%
c('leaflet','local','campaigning','branding') ~ "ABC",
TRUE ~ source))
# source amount
#1 mercury 100
#2 inbound 99
#3 ABC 101
#4 ABC 87
#5 ABC 123
#6 ABC 99
df <- structure(list(source = c("mercury", "inbound", "leaflet", "local",
"campaigning", "branding"), amount = c(100, 99, 101, 87, 123,
99)), class = "data.frame", row.names = c(NA, -6L))
Upvotes: 1
Reputation: 388982
You can update the values of source
as
df$source[df$source %in% c('leaflet','local','campaigning','branding')] <- "ABC"
df
# source amount
#1 mercury 100
#2 inbound 99
#3 ABC 101
#4 ABC 87
#5 ABC 123
#6 ABC 99
data
Make sure to have character data instead of factors.
df <- data.frame(source = c('mercury','inbound','leaflet','local','campaigning',
'branding'),amount = c(100,99,101,87,123,99), stringsAsFactors = FALSE)
Upvotes: 0