简体   繁体   English

如何将函数应用于列表中的向量

[英]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). 向量列表为:(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. 该函数确定矢量元素和它们的sum(n)减去前一个元素的组合,并返回它们之间的乘积。 Ex: (3,3) => 6C3.3C3 = 20; 例如:(3,3)=> 6C3.3C3 = 20; (3,2,1) => (6C3)(3C2)(1C1) = 60 and so on. (3,2,1)=>(6C3)(3C2)(1C1)= 60依此类推。

Wen I apply this to the entire list, using sapply, the output is undesirable. Wen我将此应用到整个列表,使用sapply,输出是不可取的。

> 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). 因此,在应用函数后,我应该有一个整数列表,即(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. 不需要两个函数,只需combVecFunc完成纠正后的要求。

  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). 用于choose一次而不是comb的基R函数(用于计算一次取kn元素的组合数)(甚至不存在并且抛出错误)。
  2. The function should take only one input argument, the sum n can be computed by the function itself. 该函数应仅接受一个输入参数,总和n可以由函数本身计算。

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. 用户@Cole的注释可以使函数更简单。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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