Karthik S
Karthik S

Reputation: 11584

update table where column in equivalent in R

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

Answers (2)

akrun
akrun

Reputation: 887158

We can use case_whenfrom 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

data

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

Ronak Shah
Ronak Shah

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

Related Questions