我在r中有这个矩阵,它有两列,形状和比例。
现在我有10000行,我需要的是在下面应用此代码:
rw <- rweibull(10, shape=, scale=)
我需要循环遍历矩阵的每一行以计算rw。 任何帮助将不胜感激。
由于
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")))
答案 0 :(得分:2)
您可以使用mapply
。
mapply(rweibull, n = 10L, shape = mat[,"shape"], scale = mat[,"scale_ima"])
答案 1 :(得分:1)
虽然我认为rowwise
apply
操作更自然,mapply
似乎更快一点
apply(mat, 1, function(x) rweibull(10, shape=x[1], scale=x[2]))
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