# R Looping through two vectors

### Tags:

#### 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) 796 asked Jan 25 '23 21:01

#### TrainedMusician

You can use `outer`:
``````calculateIDVectorized <- function(p, r) as.vector(t(outer(p, r, calculateID))) 158 answered Jan 29 '23 17:01