How to code elementary symmetric polynomials in R

Take the product of each combination using combn(x, k, prod) and then sum that:

sympoly <- function(k, x) sum(combn(x, k, prod))

sapply(0:4, sympoly, 1:4)
## [1]  1 10 35 50 24

The solution is not crossprod, it's combn/prod followed by sum.

elSymPoly <- function(x){
  sapply(c(0, seq_along(x)), function(n){
    sum(apply(combn(x, n), 2, prod))
  })
}

x <- c(1, 2, 3, 4)
elSymPoly(x)
#[1]  1 10 35 50 24

Note that the function also works with an empty vector (but not with NULL).

y <- integer(0)
elSymPoly(y)
#[1] 1

Tags:

Function

R