So, I'm new to R (I'm starting out from the Python background), and I'm still having problems understanding how / when to implement the apply functions (lapply, sapply, rapply, etc.) instead of nested loops.
As an example, suppose you want to execute a FUN function that compares each item in a list with each item in another list. I would write something like:
n = 1 m = 1 sameList = NULL for(i in 1:length(list1)){ for(j in 1:length(list2)){ if(list1[n]==list2[m]){ sameList<-c(sameList, list1[n]} n = n+1 } m = m+1 }
In other words, some nested loop that iterates through each element of each list.
What I'm learning is that concatenating an intermediate list loop is a very inefficient process in R, so apply used.
So, how would I use apply (or any version of it) to replace the example code above?
source share