当某些参数是常量而某些参数不是时,应用函数

时间:2018-04-21 19:17:29

标签: loops for-loop lapply

我需要计算CVfromCI。在此函数中,参数lowerupperpen是不同的;参数designalpharobust是常量。如何缩短代码?目前我需要每次从开始到结束都写它们。

library(PowerTOST)

CVfromCI(pe = 0.95, lower = 0.86, upper = 1.029, n = 24, design = "2x2", alpha = 0.05, robust = FALSE)
CVfromCI(pe = 0.94, lower = 0.897, upper = 1.027, n = 24, design = "2x2", alpha = 0.05, robust = FALSE)
CVfromCI(pe = 0.99, lower = 0.88, upper = 1.025, n = 24, design = "2x2", alpha = 0.05, robust = FALSE)

1 个答案:

答案 0 :(得分:0)

我们可以使用mapply将函数CVfromCI应用于多个参数。

library(PowerTOST)

mapply(CVfromCI, 
       pe = c(0.95, 0.94, 0.99),
       lower = c(0.86, 0.897, 0.88),
       upper = c(1.029, 1.027, 1.025),
       n = 24,
       design = "2x2",
       alpha = 0.05,
       robust = FALSE)
# [1] 0.1824596 0.1371548 0.1547650
# Warning messages:
# 1: sigma based on pe & lower CL more than 10% different than
# sigma based on pe & upper CL. Check input. 
# 2: sigma based on pe & lower CL more than 10% different than
# sigma based on pe & upper CL. Check input. 
# 3: sigma based on pe & lower CL more than 10% different than
# sigma based on pe & upper CL. Check input.

我们也可以使用包中的pmap_dbl。请注意,在使用pmap_dbl时,我们首先提供多个参数作为列表,然后是函数。

library(purrr)

pmap_dbl(list(pe = c(0.95, 0.94, 0.99),
              lower = c(0.86, 0.897, 0.88),
              upper = c(1.029, 1.027, 1.025),
              n = 24,
              design = "2x2",
              alpha = 0.05,
              robust = FALSE),
         CVfromCI)
# [1] 0.1824596 0.1371548 0.1547650
# Warning messages:
# 1: sigma based on pe & lower CL more than 10% different than
# sigma based on pe & upper CL. Check input. 
# 2: sigma based on pe & lower CL more than 10% different than
# sigma based on pe & upper CL. Check input. 
# 3: sigma based on pe & lower CL more than 10% different than
# sigma based on pe & upper CL. Check input.