Bing
Bing

Reputation: 57

Add value in one column based on multiple key words in another column in r

I want to do the following things: if key words "GARAGE", "PARKING", "LOT" exist in column "Name" then I would add value "Parking&Garage" into column "Type".

Here is the dataset:

df<-data.frame(Name=c("GARAGE 1","GARAGE 2", "101 GARAGE","PARKING LOT","CENTRAL PARKING","SCHOOL PARKING 1","CITY HALL"))

The following codes work well for me, but is there a neat way to make the codes shorter? Thanks!

df$Type[grepl("GARAGE", df$Name) | 
                       grepl("PARKING", df$Name) |
                          grepl("LOT", df$Name)]<-"Parking&Garage"

Upvotes: 0

Views: 85

Answers (3)

Ronak Shah
Ronak Shah

Reputation: 389012

You can create a list of keywords to change, create a pattern dynamically and replace the values.

keywords <- c('GARAGE', 'PARKING', 'LOT')
df$Type <- NA
df$Type[grep(paste0(keywords, collapse = '|'), df$Name)] <- "Parking&Garage"
df

#              Name           Type
#1         GARAGE 1 Parking&Garage
#2         GARAGE 2 Parking&Garage
#3       101 GARAGE Parking&Garage
#4      PARKING LOT Parking&Garage
#5  CENTRAL PARKING Parking&Garage
#6 SCHOOL PARKING 1 Parking&Garage
#7        CITY HALL           <NA>

This would be helpful if you need to add more keywords to your list later.

Upvotes: 1

DPH
DPH

Reputation: 4344

an alternative with dpylr and stringr packages:

library(stringr)
library(dplyr)

df %>% 
  dplyr::mutate(TYPE = stringr::str_detect(Name, "GARAGE|PARKING|LOT"),
            TYPE = ifelse(TYPE == TRUE, "Parking&Garage", NA_character_))

Upvotes: 0

Dubukay
Dubukay

Reputation: 2071

The regex "or" operator | is your friend here:

df$Type[grepl("GARAGE|PARKING|LOT", df$Name)]<-"Parking&Garage"

enter image description here

Upvotes: 1

Related Questions