R 中的多项式函数展开

Polynomial Function Expansion in R

我目前正在 SO 上查看此问题,发现 OP 指出通过添加更多 for 循环可以扩展多项式。你会怎么做?我正在尝试扩展到 polyorder 5。

Polynomial feature expansion in 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)
}

最终,我想订购 so that it expands in order of degree. I tried using the poly function but I'm not sure if you can order the result so that it returns a ,从 1 级开始,然后移动到 2 级,然后是 3、4 和 5。

对"sort by degree"有点暧昧。 x^2x*y 的度数都是 2。我假设您想按总度数排序,然后在每个度数中按第一列的度数排序;在其中,按第二列的度数等。(我相信默认设置是忽略总度数并按最后一列的度数排序,在倒数第二列中,依此类推,但这没有记录,所以我不会'别指望了。)

以下是如何使用 polym 执行此操作。这些列的名称类似于 "2.0""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 package (v0.3.0)

于 2020-03-21 创建