【问题标题】:Is it possible to `for` loop the `sapply` in R?是否可以在 R 中“for”循环“sapply”?
【发布时间】:2017-12-26 19:55:09
【问题描述】:

我想知道为什么我的对象 CI 在以下函数中没有正确返回来自 for() 循环的完整(11 个配对答案)输出?相反,CI 返回 11 个单个数字。

N = 30 ; df = 118 ; d = 1

f <- function (ncp, alpha, q, df) {
 abs(suppressWarnings(pt(q = d*sqrt(N), df = df, ncp, lower.tail = FALSE)) - 
   alpha)
      }

 a = mapply(c, as.list(20:30), as.list(-20:-30), SIMPLIFY = FALSE) # a list of paired values

 CI <- numeric(length(a))

 for(i in 1:length(a)){

CI[i] = sapply(c(0.025, 0.975),
         function(x) optimize(f, interval = a[[i]], alpha = x, q = d*sqrt(N), df = df, tol = 1e-10)[[1]])

    }  

CI # just returns one paired of the 11 paired answers expected!

【问题讨论】:

    标签: r function for-loop optimization sapply


    【解决方案1】:

    怎么样:

    N = 30 ; df = 118 ; d = 1
    
    f <- function (ncp, alpha, q, df) {
      abs(suppressWarnings(pt(q = d*sqrt(N), df = df, ncp, lower.tail = FALSE)) - 
            alpha)
    }
    
    a = mapply(c, as.list(20:30), as.list(-20:-30), SIMPLIFY = FALSE) # a list of paired values
    
    CI <- matrix(NA, 11,2)
    
    for(i in 1:length(a)){
    
      CI[i,] = sapply(c(0.025, 0.975),
                  function(x) optimize(f, interval = a[[i]], alpha = x, q = d*sqrt(N), df = df, tol = 1e-10)[[1]])
    
    }  
    
    CI
    

    【讨论】:

    • 谢谢您,在等待系统允许我接受您的回答时,一个问题,如何找到11行中出现频率最高的答案(行)?
    • @rnorouzian,解决方案并不完全相等。见 CI[4,] == CI[5]。所以你可能需要对它们进行四舍五入,例如library(dplyr) ;summarise(group_by(as.data.frame(round(CI,4)),V1,V2),length(V2))
    猜你喜欢
    • 1970-01-01
    • 2013-11-13
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-21
    相关资源
    最近更新 更多