Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Basic understanding of using 'apply' instead of nested loop

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?

like image 615
tomathon Avatar asked Apr 07 '14 15:04

tomathon


People also ask

Why is apply better than for loop?

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.

Should you avoid nested 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.

How do you use a nested loop in R?

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.


1 Answers

To use lapply, you would run:

sameList = lapply(list1, function(x) lapply(list2, function(y) if (x==y) x else NULL))
like image 102
Señor O Avatar answered Oct 24 '22 18:10

Señor O