【问题标题】:subtracting unique pair-wise objects from for loop in R从R中的for循环中减去唯一的成对对象
【发布时间】:2018-01-10 16:42:22
【问题描述】:

我正在尝试从下面我的函数中的for 循环中减去每个唯一的成对 ps。为此,我首先使用combn(p, 2)找到唯一的成对ps,第二使用outer减去每个唯一的互相配对。

在这两个步骤中,我都会出错。有没有解决这个错误的办法?

prop <- function(n, yes, a, b = a){

    p <- list()

    for(i in 1:length(n)){
        p[[i]] <- rbeta(2, a[i] + yes[i], b[i] + (n[i] - yes[i]))
    }
    outer(combn(p, 2), FUN = "-")    # Gives Error
}

prop(n = c(10, 20, 30), yes = rep(5, 3), a = rep(1, 3))

【问题讨论】:

    标签: r function for-loop combinations


    【解决方案1】:

    默认为combn中的simplify = TRUE。因此,即使输出是list,通过将每个list 转换为matrix 中的元素,它也被简化为具有dim 属性。由于m 为2,因此每次比较有2 个list 元素,使用[[ 提取这些元素并减去

    combn(p, 2, FUN = function(x) x[[1]]- x[[2]])
    

    -全功能

    prop <- function(n, yes, a, b = a){
    
       p <- list()
    
       for(i in 1:length(n)){
         p[[i]] <- rbeta(2, a[i] + yes[i], b[i] + (n[i] - yes[i]))
        }
        combn(p, 2, FUN = function(x) x[[1]]- x[[2]])
       }
    
    prop(n = c(10, 20, 30), yes = rep(5, 3), a = rep(1, 3))
    

    如果我们想包含另一个参数how

    prop <- function(n, yes, a, b = a, how= "one.two"){
      delta <- switch(how, 
                 one.two = function(x) x[[1]] - x[[2]],
                 two.one = function(x) x[[2]] - x[[1]])
      p <- list()
    
      for(i in 1:length(n)){
         p[[i]] <- rbeta(2, a[i] + yes[i], b[i] + (n[i] - yes[i]))
       }
    
        out <-  combn(p, 2, FUN = delta)
        nm1 <- paste0("p", combn(seq_along(p), 2, FUN = paste, collapse="-"))
        colnames(out) <- nm1
        out
    
     }
    
    prop(n = c(10, 20, 30), yes = rep(5, 3), a = rep(1, 3), how = "one.two")
    
    prop(n = c(10, 20, 30), yes = rep(5, 3), a = rep(1, 3), how = "two.one")
    

    【讨论】:

      猜你喜欢
      • 2022-12-24
      • 2011-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-03
      • 2018-09-10
      • 1970-01-01
      相关资源
      最近更新 更多