Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to code elementary symmetric polynomials in R

Tags:

function

r

I want to program a function in R that compute the elementary symmetric polynomials. For i=0, 1, ..., p, the i-th elementary polynomial is given by

enter image description here

How can I code this function in R? I've tried

x<-c(1,2,3,4)
crossprod(x)
# or
for (i in 1:length(x)) print(crossprod((combn(x,i))))

but I don't get the desired result, which is supposed to give

e0= 1

e1= 10

e2= 35

e3= 50

e4= 24

like image 418
coolsv Avatar asked Jul 27 '19 16:07

coolsv


2 Answers

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
like image 150
G. Grothendieck Avatar answered Nov 15 '22 08:11

G. Grothendieck


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
like image 23
Rui Barradas Avatar answered Nov 15 '22 08:11

Rui Barradas