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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With