[R] Alternative to loops

Ek Esawi e@@w|ek @end|ng |rom gm@||@com
Sat Apr 6 19:44:55 CEST 2019

Thank you. Sorry i forgot to turn off the html

Below is a sample of my data. My original data frame has over 10,000 rows.
I want to check each element on my data frame column B
(MyDF$B) to see if it contains any element(s) of MYList. if os, change
the value of MyDF$C to the name of the vector of the list that has

I solved this via loops and if statements, using &in&  but I am hoping for
a more compact solution using the apply family functions. I tried something like
this but did not work.

lapply(strsplit(MyDF$B," "),function(x) lapply(MyList,function(y)  if(sum(y
%in% x)>0,x$Code==y[[1]]))

Thanks in advance--EK

Sample data
MyList <- list(X=c("a","ba","cc"),Y=c("abs","aa","BA","BB"),z=c("ab","bb","xy","zy","gh"))
MyDF <- data.frame(A=c(1,2,3,4,5),B=c("aa ab ac","bb bc bd","cc
cf","dd","ee"), C= c(0,0,0,0,0), stringsAsFactors = FALSE)

> MyDF

    A     B      C
1 1 aa ab ac  0
2 2 bb bc bd  0
3 3    cc cf     0
4 4       dd     0
5 5       ee     0

> MyList

[1] "a"  "ba" "cc"

[1] "abs" "aa"  "BA"  "BB"

[1] "ab" "bb" "xy" "zy" "gh"

Desired results.

> MyDF

   A     B        C
1 1 aa ab ac Y
2 2 bb bc bd Y
3 3    cc cf    X
4 4       dd     0
5 5       ee     0

More information about the R-help mailing list