R中t分布的矢量化
我需要在R中t分布的矢量化,r,vectorization,R,Vectorization,我需要在R的rtt分布采样器中对非中心性参数进行矢量化。然而,当我给出: rt(2, df = 1, ncp = c(1,2)) 我明白了 Warning message: In if (is.na(ncp)) { : the condition has length > 1 and only the first element will be used 其他函数,如rbinom或rgama没有类似的问题(即rbinom中的prob参数可以像rgama的比例参数一样进行矢量化) 有
R
的rt
t分布采样器中对非中心性参数进行矢量化。然而,当我给出:
rt(2, df = 1, ncp = c(1,2))
我明白了
Warning message:
In if (is.na(ncp)) { :
the condition has length > 1 and only the first element will be used
其他函数,如rbinom
或rgama
没有类似的问题(即rbinom
中的prob
参数可以像rgama
的比例参数一样进行矢量化)
有没有办法做到这一点(没有循环)?您可以使用
sapply
:
sapply( 1:3, function(x) rt(2, df = 1, ncp = x) )
# [,1] [,2] [,3]
# [1,] 0.3881308 1.905535 1.781836
# [2,] -0.7950962 2.905824 1.633683
结果矩阵中的每一列对应于不同的
ncp
值。您可以使用sapply
:
sapply( 1:3, function(x) rt(2, df = 1, ncp = x) )
# [,1] [,2] [,3]
# [1,] 0.3881308 1.905535 1.781836
# [2,] -0.7950962 2.905824 1.633683
结果矩阵中的每列对应于不同的
ncp
值。您可以使用性能类似的lappy
、sapply
或vapply
Lappy
和vapply
比sapply
快一点,因为sapply
是Lappy
的包装,它试图使结果更漂亮/更简单
microbenchmark::microbenchmark(
vapply(c(1,2, 3), function(x) rt(2, df = 1, ncp=x), numeric(2L)),
sapply( 1:3, function(x) rt(2, df = 1, ncp = x) ),
lapply( 1:3, function(x) rt(2, df = 1, ncp = x) ),
vec.rt(2, df=1, ncp=1:3))
#Unit: microseconds
# expr min lq mean median uq max neval cld
#vapply 27.121 37.6095 51.61055 39.8825 42.4570 1226.199 100 a
#sapply 51.438 58.1725 72.89417 60.9150 63.4850 1255.270 100 ab
#lapply 29.484 34.0670 59.78256 36.8160 39.0755 2326.401 100 ab
#vec.rt 95.511 101.6985 106.15785 105.0770 108.2700 189.312 100 b
您可以使用性能类似的
lappy
、sapply
或vapply
Lappy
和vapply
比sapply
快一点,因为sapply
是Lappy
的包装,它试图使结果更漂亮/更简单
microbenchmark::microbenchmark(
vapply(c(1,2, 3), function(x) rt(2, df = 1, ncp=x), numeric(2L)),
sapply( 1:3, function(x) rt(2, df = 1, ncp = x) ),
lapply( 1:3, function(x) rt(2, df = 1, ncp = x) ),
vec.rt(2, df=1, ncp=1:3))
#Unit: microseconds
# expr min lq mean median uq max neval cld
#vapply 27.121 37.6095 51.61055 39.8825 42.4570 1226.199 100 a
#sapply 51.438 58.1725 72.89417 60.9150 63.4850 1255.270 100 ab
#lapply 29.484 34.0670 59.78256 36.8160 39.0755 2326.401 100 ab
#vec.rt 95.511 101.6985 106.15785 105.0770 108.2700 189.312 100 b
另一个选项是使用
Vectorize
创建伪矢量化函数。例如,要针对ncp
参数对rt
进行矢量化,可以执行以下操作:
vec.rt <- Vectorize(rt, "ncp")
请注意,这并没有为您提供真正的矢量化函数,也不会
sapply
或lappy
。所有这些函数都在内部使用循环,因此与干净编写的for
构造相比,您不会注意到任何性能提高。另一个选项是使用向量化创建伪向量化函数。例如,要针对ncp
参数对rt
进行矢量化,可以执行以下操作:
vec.rt <- Vectorize(rt, "ncp")
请注意,这并没有为您提供真正的矢量化函数,也不会sapply
或lappy
。所有这些函数都在内部使用循环,因此与干净编写的for
构造相比,您不会注意到任何性能提高。感谢您的比较!需要记住的一点是,sapply
是lappy
的包装器,并且有一个额外的简化步骤,将输出转换为矩阵,这会增加其运行时间。感谢您的比较!需要记住的一点是,sapply
是lappy
的包装器,并且有一个额外的简化步骤,将输出转换为矩阵,这会增加其运行时间。