Reputation: 95
I’m trying to a key word search based on a couple of conditions. My code below creates some example data and tries to work this through. It doesn’t like the ifelse, I believe since GREP doesn’t actually return a true/false, but instead the actual data. I’m thinking I’d have to create a subset, then merge it back in? However, I can’t seem to put more than 1 condition in the subset with a GREP.
Any help is much appreciated!
bus_name <- c('jacks wok shop'
,'jacks ski shop'
,'jacks wokshop'
,'jacks bakery'
,'jacks business'
,'jims Brewery'
,'jims Wok Brewery'
)
type <- c('restaurant'
,'restaurant'
,'restaurant'
,'restaurant'
,'office'
,'store'
,'building'
)
mydata <- data.frame(bus_name, type)
mydata$bus_name <- as.character(mydata$bus_name)
mydata$type <- as.character(mydata$type)
mydata$flag <- ifelse(mydata$type == "restaurant" & mydata[grep("WOK",toupper(mydata$bus_name)),],"Wok",
ifelse(mydata$type == "office" & mydata[grep("BUSINESS",toupper(mydata$bus_name)),],"Business","0"))
The ideal output would be the following:
bus_name|type|flag
jacks wok shop|restaurant|Wok
jacks ski shop|restaurant
jacks wokshop|restaurant|Wok
jacks bakery|restaurant
jacks business|office|Business
jims Brewery|store
jims Wok Brewery|building|Wok
Upvotes: 1
Views: 152
Reputation: 16277
You have to use grepl
to get a logical vector of TRUE/FALSE. You could use case_when
from dplyr
. It's easier to read than nested ifelse
.
library(dplyr)
mydata %>%
mutate(flag=case_when(
.$type == "restaurant" & grepl("WOK",toupper(.$bus_name)) ~ "Wok",
.$type == "office" & grepl("BUSINESS",toupper(.$bus_name)) ~ "Business",
TRUE ~ "0"
))
bus_name type flag
1 jacks wok shop restaurant Wok
2 jacks ski shop restaurant 0
3 jacks wokshop restaurant Wok
4 jacks bakery restaurant 0
5 jacks business office Business
6 jims Brewery store 0
7 jims Wok Brewery building 0
Upvotes: 2
Reputation: 18425
grepl
is the function to use if you want logical values. You need something like this
mydata$flag <- ifelse(mydata$type == "restaurant" & grepl("WOK",toupper(mydata$bus_name)),
"Wok",
ifelse(mydata$type == "office" & grepl("BUSINESS",toupper(mydata$bus_name)),
"Business",""))
Upvotes: 1