简体   繁体   中英

How can I apply a function to vectors in a list

I have a list of vectors, I wish to apply a function I created to the list of vectors that should only return one integer. The list of vectors are: (3,3);(3,2,1);(3,1,1,1).

alpha.6.3 <- list(c(3, 3), c(3, 2, 1), c(3, 1, 1, 1))

The function determines the combination of the vector elements and their sum(n) minus the previous element, and returns the product between them. Ex: (3,3) => 6C3.3C3 = 20; (3,2,1) => (6C3)(3C2)(1C1) = 60 and so on.

Wen I apply this to the entire list, using sapply, the output is undesirable.

> list 
[[1]]
[1] 3 3

[[2]]
[1] 1 2 3

[[3]]
[1] 1 1 1 3

combVecFunc <-  function(n,x){
  ans = c()

  for(j in 1:length(x)){
    ans[j] = comb(n,x[j])
    n = n-x[j]
  }
  print(prod(ans))
}

prodVecFunc <- function(n,list){

  ans <- sapply(list, function(i){
    x <- c()
      for(i in 1:length(list)){
        x[i]<- combVecFunc(n,list[[i]])
      }
      return(x)
    })
  print(ans)
}

> prodVecFunc(n=6,list)
[1] 20
[1] 60
[1] 120
[1] 20
[1] 60
[1] 120
[1] 20
[1] 60
[1] 120
     [,1] [,2] [,3]
[1,]   20   20   20
[2,]   60   60   60
[3,]  120  120  120

Thus I should have a list of integers after the function is applied namely (20,60,120). Rather than the vector with multiple answers.

There is no need for two functions, just combVecFunc will do what is asked for after corrected.

  1. The base R function to compute the number of combinations of n elements taken k at a time is choose , not comb (that doesn't even exist and was throwing an error).
  2. The function should take only one input argument, the sum n can be computed by the function itself.

So the code would become the following.

combVecFunc <-  function(x){
  n <- sum(x)
  ans = numeric(length(x))

  for(j in seq_along(x)){
    ans[j] = choose(n, x[j])
    n = n - x[j]
  }
  prod(ans)
}

alpha.6.3 <- list(c(3, 3), c(3, 2, 1), c(3, 1, 1, 1))

sapply(alpha.6.3, combVecFunc)
#[1]  20  60 120

Edit.

The comment by user @Cole can make the function much simpler.

combVecFunc2 <-  function(x){
  n <- sum(x)
  ans <- choose(n - c(0, cumsum(x[-length(x)])), x)
  prod(ans)
}

sapply(alpha.6.3, combVecFunc2)
#[1]  20  60 120

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM