So I am new to R (I come from a Python background) and I am still having some issues understanding how/when to implement apply
functions (lapply, sapply, rapply, etc) instead of nested loops.
As an example, suppose you wanted to perform some function FUN that compared each element of list to each element of another list. I would write something along the lines of:
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 over every element of each list.
What I am learning is that concatenating a list mid-loop is a very inefficient process in R, which is why apply
is used.
So how would apply
(or any version of it) be used to replace the above example code?
The apply functions do run a for loop in the background. However they often do it in the C programming language (which is used to build R). This does make the apply functions a few milliseconds faster than regular for loops.
One reason to avoid nesting loops is because it's a bad idea to nest block structures too deeply, irrespective of whether they're loops or not.
Nested for loops are used to manipulate a matrix by making a specific setting to a specific value and considered as a foundation skill in R Programming. This is more beneficial if we wish to extract a specific value from the corresponding row and column index.
To use lapply
, you would run:
sameList = lapply(list1, function(x) lapply(list2, function(y) if (x==y) x else NULL))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With