首页 > 解决方案 > R中的多项式函数展开

问题描述

我目前正在审查这个问题,SO并看到OP说明通过添加更多 for 循环可以扩展多项式。你会怎么做呢?我正在尝试扩展到多阶 5。

R中的多项式特征扩展

下面是代码:

polyexp = function(df){
  df.polyexp = df
  colnames = colnames(df)
  for (i in 1:ncol(df)){
    for (j in i:ncol(df)){
      colnames = c(colnames, paste0(names(df)[i],'.',names(df)[j]))
      df.polyexp = cbind(df.polyexp, df[,i]*df[,j])
    }
  }
  names(df.polyexp) = colnames
  return(df.polyexp)
}

最终,我想对进行排序,以便它按程度顺序扩展。我尝试使用 poly 函数,但我不确定您是否可以对结果进行排序,以便它返回一个以 1 度开始然后移动到 2 度、然后是 3、4 和 5的

标签: rmatrixpolynomials

解决方案


“按程度排序”有点模棱两可。 x^2并且x*y都具有 2 级。我假设您要按总度数排序,然后在每个度数中按第一列的度数排序;在那之内,按第二列的度数等(我相信默认是忽略总度数并按最后一列的度数排序,在倒数第二列之内,依此类推,但这没有记录,所以我不会'不要指望它。)

以下是如何使用polym来做到这一点。"2.0"这些列被命名为or之类的东西"1.1"。您可以按字母顺序对这些名称进行排序,最高可达 9 级,但如果您使用 转换这些名称as.numeric_version,则没有限制。因此,将列名转换为版本名,获取排序顺序,并使用该加度对结果的列进行重新排序。例如,

df <- data.frame(x = 1:6, y = 0:5, z = -(1:6))

expanded <- polym(as.matrix(df), degree = 5)

o <- order(attr(expanded, "degree"),
           as.numeric_version(colnames(expanded)))

sorted <- expanded[,o]
# That lost the attributes, so put them back
attr(sorted, "degree") <- attr(expanded, "degree")[o]
attr(sorted, "coefs") <- attr(expanded, "coefs")
class(sorted) <- class(expanded)

# If you call predict(), it comes out in the default order,
# so will need sorting too:

predict(sorted, newdata = as.matrix(df[1,]))[, o]
#>       0.0.1       0.1.0       1.0.0       0.0.2       0.1.1       0.2.0 
#>  0.59761430 -0.59761430 -0.59761430  0.54554473 -0.35714286  0.54554473 
#>       1.0.1       1.1.0       2.0.0       0.0.3       0.1.2       0.2.1 
#> -0.35714286  0.35714286  0.54554473  0.37267800 -0.32602533  0.32602533 
#>       0.3.0       1.0.2       1.1.1       1.2.0       2.0.1       2.1.0 
#> -0.37267800 -0.32602533  0.21343368 -0.32602533  0.32602533 -0.32602533 
#>       3.0.0       0.0.4       0.1.3       0.2.2       0.3.1       0.4.0 
#> -0.37267800  0.18898224 -0.22271770  0.29761905 -0.22271770  0.18898224 
#>       1.0.3       1.1.2       1.2.1       1.3.0       2.0.2       2.1.1 
#> -0.22271770  0.19483740 -0.19483740  0.22271770  0.29761905 -0.19483740 
#>       2.2.0       3.0.1       3.1.0       4.0.0       0.0.5       0.1.4 
#>  0.29761905 -0.22271770  0.22271770  0.18898224  0.06299408 -0.11293849 
#>       0.2.3       0.3.2       0.4.1       0.5.0       1.0.4       1.1.3 
#>  0.20331252 -0.20331252  0.11293849 -0.06299408 -0.11293849  0.13309928 
#>       1.2.2       1.3.1       1.4.0       2.0.3       2.1.2       2.2.1 
#> -0.17786140  0.13309928 -0.11293849  0.20331252 -0.17786140  0.17786140 
#>       2.3.0       3.0.2       3.1.1       3.2.0       4.0.1       4.1.0 
#> -0.20331252 -0.20331252  0.13309928 -0.20331252  0.11293849 -0.11293849 
#>       5.0.0 
#> -0.06299408

reprex 包于 2020-03-21 创建(v0.3.0)


推荐阅读