Eric Eric - 1 day ago 6
R Question

Variable number of Inputs for the Function - R

I have the following function that

A
and
B
indicate vector as inputs. My question is how I can have different number of vetors for this function. In my function,
n
is fixed and shows the number of samples. For example, I need that my function works for this case as well:
sample_sum (A, B, C, D, E, n, ...)
.
Also for the part that I get samples of vector A and B (i.e. in line
sample_A <- qss(A, n=n, ...)
) how I can modify it for different number of vectors not using
for
loop since
for
loop is not fast enough.

Thanks

sample_sum <- function(A, B, n, ...)
{
qss <- function(X, n, ...)
{
r_X <- range(X)
dens_X <- density(X, ...)
sample(dens_X$x, size=n, prob=dens_X$y, replace=TRUE)
}
sample_A <- qss(A, n=n, ...)
sample_B <- qss(B, n=n, ...)
sample_A + sample_B
}

Answer

I think what you need is the following:

new_sample_sum <- function(my_vector_list, n, ...)
{
  qss <- function(X, n, ...)
  {
    r_X <- range(X)
    dens_X <- density(X, ...)
    sample(dens_X$x, size=n, prob=dens_X$y, replace=TRUE)
  }

  rowSums(sapply(my_vector_list, qss, n = n))

}

You can put multiple vectors in your vector list and then do your calculations over the list without worrying about the number of vectors. Just a brief note on the calculations, sapply will loop over all vectors in the list and then return a table with all the results of applying qss to each vector (For every vector the result is one column in the table that sapply returns). Since you add the vectors in the final step of your function I do a rowSums of the table with all the results.

And in order to prove the consistency:

set.seed(1)
x <- c(1,2,3,4)
y <- c(6,7,9,0)
z <- c(2,2,2,2)

> sample_sum(x, y, n=2)
[1]  6.545129 13.474390

> new_sample_sum(list(x, y), n = 2)
[1]  6.545129 13.474390

Or with more vectors:

sample_sum <- function(A, B, C, n, ...)
{
  qss <- function(X, n, ...)
  {
    r_X <- range(X)
    dens_X <- density(X, ...)
    sample(dens_X$x, size=n, prob=dens_X$y, replace=TRUE)
  }
  sample_A <- qss(A, n=n, ...)
  sample_B <- qss(B, n=n, ...)
  sample_C <- qss(C, n=n, ...)
  sample_A + sample_B + sample_C
}

set.seed(1)
> sample_sum(x, y, z, n = 2)
[1]  6.102482 15.450364
set.seed(1)
> new_sample_sum(list(x, y, z), n = 2)
[1]  6.102482 15.450364
Comments