从R中的for循环中减去唯一的成对对象

时间:2018-01-10 16:42:23

标签: r function for-loop combinations

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

在这两个步骤中,我都会收到错误消息。是否有错误修复?

outer

1 个答案:

答案 0 :(得分:3)

默认情况下,simplify = TRUEcombn。因此,即使输出为list,也可以通过将dim中的每个list转换为matrix中的元素来简化为m属性。由于list为2,每次比较都有2 [[个元素,使用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))

-full function

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")

@keyframes line_draw{ 100%{ width: 100vh; } }