Hoffmann
Hoffmann

Reputation: 1082

Use matrix as lookup table in R for vectors

I have columns

sex <- c(1, 2, 1)
age <- c(12, 13, 14)

and a lookup table

bmi_adipos_limit_table = array(c(24.77, 24.91, 25.02, 24.65, 24.92, 25.18), dim = c(4,2))

and woud like to do

bmi_adipos_limits <- magicFunction(age, sex)

with

bmi_adipos = c(24.77, 24.92, 25.02)

I tried

bmi_adipos = bmi_adipos_limits[age-11, sex]

which did not work (return value was what I would have expected from bmi_adipos_limits[(age-11) X sex]). So can someone give me a hint what this magicFunction I'm looking for is?

Upvotes: 1

Views: 770

Answers (1)

Justin
Justin

Reputation: 43265

You're looking for mapply:

mysubsetter <- function(x, y) {
    bmi_adipos_limit_table[x-11, y]
} 

mapply(mysubsetter, age, ex)
# [1] 24.77 25.18 25.02

Upvotes: 2

Related Questions