rnorouzian
rnorouzian

Reputation: 7517

Why only working when arguments have a length >= 3: R function

I have made a function so that it works when its arguments each have a length >= 2.

But I'm wondering why the function only works when its argument have each have a length of >= 3!

Am I missing something? (Any fix so the function works when length of its args are each of 2 as well?)

[Note: I always expect the output of function (i.e., CI) to be a matrix with 2 columns, length(n) rows, except when length(n) == 2. When length(n) == 2 I expect the output to have 1 row, and 2 columns.]

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

  p <- list()

 for(i in 1:length(n)){
   p[[i]] <- rbeta(1e3, a[i] + yes[i], b[i] + (n[i] - yes[i]))
   }
 ps <- combn(p, 2, FUN = function(x) x[[1]]- x[[2]])

 CI <- matrix(NA, length(n), 2)

 for(i in 1:length(n)){
 CI[i, ] <- quantile(ps[, i], c(.025, .975))
   }
 CI
  }

For example:

  abc(n = c(10, 20, 30), yes = rep(5, 3), a = rep(1, 3)) # Works well :-)

  abc(n = c(10, 20), yes = rep(5, 2), a = rep(1, 2))  # Doesn't work! :-(
  # Error in ps[, i] : subscript out of bounds

Upvotes: 1

Views: 52

Answers (1)

MKR
MKR

Reputation: 20095

There is easy fix to problem. Replace length(n) with ncol(ps) while creating result matrix and running for loop to copy values to CI. It makes more sense as number of combinations generate by 'combnwill more than actual length ofn`.

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

  p <- list()

  for(i in 1:length(n)){
    p[[i]] <- rbeta(1e3, a[i] + yes[i], b[i] + (n[i] - yes[i]))
  }

  str(p)

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


  CI <- matrix(NA, ncol(ps), 2)

  for(i in 1:ncol(ps)){
    CI[i, ] <- quantile(ps[, i], c(.025, .975), na.rm = TRUE)
  }
  CI
}


#Results
#> abc(n = c(10, 20, 30), yes = rep(5, 3), a = rep(1, 3))
#           [,1]      [,2]
#[1,] -0.10141014 0.5774627
#[2,]  0.02638096 0.6159326
#[3,] -0.12473451 0.3069135

#> abc(n = c(10, 20), yes = rep(5, 2), a = rep(1, 2))
#           [,1]      [,2]
#[1,] -0.1228497 0.5304606

Upvotes: 1

Related Questions