1n1
1n1

Reputation: 15

Access each row of a matrix and apply to function

I have this matrix in r which has two columns, shape and scale.

Now i have 10000 rows, what i need is to apply this code below:

rw <- rweibull(10, shape=, scale=)

I need to loop through each row of the matrix in order to calculate the rw. Any help would be appreciated.

Thanks

Output for dput(head(mat, 10))

structure(c(0.953866743, 0.939544872, 0.88055226, 0.937567804, 
0.902443856, 0.969984293, 0.953468872, 0.929905045, 0.889375987, 
0.910115923, 0.152704576, 0.168592082, 0.13059434, 0.153850643, 
0.172734767, 0.162162429, 0.172533372, 0.160826152, 0.190843263, 
0.156289128), .Dim = c(10L, 2L), .Dimnames = list(NULL, c("shape", 
"scale_ima")))

Upvotes: 0

Views: 112

Answers (2)

akrun
akrun

Reputation: 887038

Although I thought rowwise operations are more natural with apply, mapply seems to be bit faster

apply(mat, 1, function(x) rweibull(10, shape=x[1], scale=x[2]))

Benchmarks

 set.seed(42)
 mat2 <- cbind(shape=rnorm(1e6, 1, 0.05), scale_ima=rnorm(1e6, 0.1, 0.05))

 f1 <- function() mapply(rweibull, n = 10L, shape = mat2[,"shape"], scale = mat2[,"scale_ima"])
 f2 <- function() apply(mat2, 1, function(x) rweibull(10L, shape=x[1], scale=x[2]))

 library(microbenchmark)
 microbenchmark(f1(),f2(), unit="relative", times=25L)
 #    Unit: relative
 # expr      min       lq   median       uq      max neval
 #f1() 1.000000 1.000000 1.000000 1.000000 1.000000    25
 #f2() 1.373051 1.323128 1.293284 1.335026 1.994696    25

Upvotes: 1

Rich Scriven
Rich Scriven

Reputation: 99331

You could use mapply.

mapply(rweibull, n = 10L, shape = mat[,"shape"], scale = mat[,"scale_ima"])

Upvotes: 2

Related Questions