Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Looping through two vectors

Tags:

performance

r

Good day,

I need a function that creates increasing ID's for two parameters. I came up with this function which works fine, but I want it to be vectorized and I cannot seem to avoid a Big O factor of N². Are there any 'better' ways to do this?

Standard function:

threshold <- 3

calculateID <- function(p, r) {
    return((p-1) * threshold + r)
}

calculateID(1, 1) #returns 1
calculateID(1, 2) #returns 2
calculateID(1, 3) #returns 3
calculateID(2, 1) #returns 4
#.....
calculateID(5, 3) #returns 15

Vectorized function, I would like to give the two parameters as vectors so the function only has to be called once:

threshold <- 3
calculateIDVectorized <- function(p, r) {
    return(unlist(
        lapply(p, function(x) {
            lapply(r, function(y) {
                (x-1) * threshold + y
            })
        })
    ))
}

calculateIDVectorized(c(1, 2, 3, 4, 5), c(1, 2, 3)) # should return 1-15

To clarify: I want that every p and r argument is used so you should always get a result of length(p * r)

like image 796
TrainedMusician Avatar asked Jan 25 '23 14:01

TrainedMusician


1 Answers

You can use outer:

calculateIDVectorized <- function(p, r) as.vector(t(outer(p, r, calculateID)))

calculateIDVectorized(c(1, 2, 3, 4, 5), c(1, 2, 3))
#> [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
like image 158
Allan Cameron Avatar answered Jan 29 '23 10:01

Allan Cameron