【问题标题】:Turning For Loop Function into Apply Function将 For 循环函数转换为 Apply 函数
【发布时间】:2017-10-08 01:12:58
【问题描述】:

在 R 中,对于一个学校项目,我试图将使用 for 循环的函数转换为使用 apply 函数的函数。

我的函数模拟泊松分布,人们可以输入参数 n、lambda 和 m。 m 是模拟次数。然后它输出 m 个 Poisson 模拟的所有均值的平均值,并输出一个 2x2 的箱形图网格,以便用户可以显示具有不同参数值的多个图。贴在下面。

我努力想办法把它变成一个使用 apply 函数的函数。由于 apply 需要一个矩阵,我是否需要已经有一个矩阵 m.out 用于我的 for 循环函数中的某些参数值。另外,我不确定该函数将使用apply。我想取矩阵中每个值的平均值。

感谢任何帮助。

Venom<-function(n,l,m){
  if(!is.numeric(c(n,l,m))){return("Error non-numeric value entered for at `enter code here`least one parameter")}
    m.out<-NULL
    for(i in 1:m){
      data1<-rpois(n,l)
      m.sim<-mean(data1)
      m.out<-rbind(m.out, m.sim)
    }
    finalmean<-mean(m.out)
    hist(m.out, main=paste("Poisson n=",n))
    return(c(finalmean, m.out))
}
par(mfrow=c(2,2))

【问题讨论】:

    标签: r for-loop apply


    【解决方案1】:

    这里有一些基本的 R 和 tidyverse 替代 for 循环。

    set.seed(0)
    n = 10
    l = 5
    m = 20
    

    首先,这是您的原始循环。我将rbind 替换为c,因为m.out 被视为向量而不是矩阵。

    m.out <- NULL
    for(i in 1:m){
      data1 <- rpois(n,l)
      m.sim <- mean(data1)
      m.out <- c(m.out, m.sim)
    }
    print(m.out)
    #  [1] 6.1 5.1 4.9 5.0 5.3 4.4 4.8 5.8 4.7 5.2 5.5 4.6 5.2 5.2 4.4 4.5 5.1 5.7 6.0 4.7
    

    基础 R

    正如您提到的,apply 采用矩阵。但是,sapply 可以使用向量作为输入和输出。

    sapply(seq_len(m), function(x) {
      mean(rpois(n, l))
    })
    

    另一个基本的 R 解决方案是使用 replicate,它将重复表达式 m 次。 simplify = T 会使其输出一个向量而不是一个列表。

    replicate(
      m,
      mean(rpois(n, l)),
      simplify = T)
    

    Tidyverse

    rerunpurrrreplicate 版本。它会产生一个列表,所以我们需要unlist这个结果。

    library('tidyverse')
    rerun(m, mean(rpois(n, l))) %>%
      unlist
    

    另一种方法是使用map_dbl,它将对向量中的每个元素应用一个函数并返回一个双精度向量。

    map_dbl(seq_len(m), ~mean(rpois(n, l)))
    

    【讨论】:

      猜你喜欢
      • 2017-06-02
      • 1970-01-01
      • 1970-01-01
      • 2016-06-12
      • 2022-12-03
      • 1970-01-01
      • 2013-05-31
      相关资源
      最近更新 更多