I'm trying to find matching string with my_list and data frame(df) and depending on TRUE/FALSE I need to populate new_name column in df with first sting in matching list (my_list[[i]][1]) in case TRUE , or "cat" column value in case no match.
My data frame is as follows:
name <- c("NETFLIX.COM", "BlueTV", "smv", "trafi", "alkatel")
cat<- c("none", "none", "none", "transportation", "communication")
df<-data.frame(name, cat)
My list:
travel<- c("travel","air_com", "AIRCAT", "tivago")
leasure<- c("leasure","MTV", "NETFLIX.COM")
my_list<- list(travel, leasure)
My for loop with ifelse and grepl is as follows:
for (j in 1:nrow(df)) {
for (i in 1:length(my_list)) {
df[j, "new_name"]<- ifelse(
grepl(paste(my_list[[i]], collapse="|"), tolower(df[j, "name"])),
my_list[[i]][1],
df[j, "cat"])
Expected output is :
df["new_name"]<- c("leasure", "none", "none", "transportation", "communication")
df
name cat new_name
1 NETFLIX.COM none leasure
2 BlueTV none none
3 smv none none
4 trafi transportation transportation
5 alkatel communication communication
Currently with the for loop I wrote I obtain exact copy of "cat" column meaning that all cases are considered as nonmatching (FALSE) in ifelse function. I'm note sure what's wrong here... Any help would be appreciated!
ifelse()
in that loop. Use anif
statement for flow control.ifelse()
is used for a vectorized selection. – user2554330