How to code elementary symmetric polynomials in R

北慕城南 提交于 2020-06-27 08:22:09

问题


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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/57233914/how-to-code-elementary-symmetric-polynomials-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!