Given the following matrix with weights in ls in the first column and heihts in the second colum:
> wgt.hgt.matrix
[,1] [,2]
[1,] 180 70
[2,] 156 67
[3,] 128 64
[4,] 118 66
[5,] 202 72
I am looking for a concise way to apply this a binary function like
function(lb, inch) { (lb/inch**2)*703 } -> bmi
to each row of the matrix, resulting in an array, list or vector of with the 5 resulting BMI values. One way I found uses the apply function:
apply(wgt.hgt.matrix, 1, function(row) bmi(row[1], row[2]))
But a splat operator as in Ruby (*) would help making the call more concise and clear:
apply(wgt.hgt.matrix, 1, function(row) bmi(*row))
Does an equivalent to the splat operator exist, i.e. a syntax element telling R to split all vector-like objects to populate argument lists? Are there other, simpler or more concise suggestion for the apply call?
Using the bmi() function as a vectorized solution is preferable since it has all vectorized operators, as was illustrated in Joshua’s answer. You can also do this with:
Unfortunately matrices are not good substrate for constructing environments using ‘with’ so coercing to a dataframe was needed above. You could get an
applysolution (which will be less time-efficient than a vectorized approach) to work with a version of bmi() re-ritten to take a vector with named elements (as created above):