r - R中的多项式函数展开
问题描述
我目前正在审查这个问题,SO
并看到OP
说明通过添加更多 for 循环可以扩展多项式。你会怎么做呢?我正在尝试扩展到多阶 5。
下面是代码:
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的矩阵。
解决方案
“按程度排序”有点模棱两可。 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)
推荐阅读
- google-apps-script - 谷歌应用脚本 - 从谷歌表发送长电子邮件 - 电子邮件分成几行
- port - wamp server 3.2.2 在 LAN 中命名为 vhost
- ssl - Bucket SSL / Bucket 的高额账单?- 谷歌云
- c++ - 使用 scanf 和 printf 使程序无限循环,但通过替换 cin 和 cout 工作正常
- mips - 虚拟内存:如果每个页表项映射一个字,需要 4 个字节,那么对于 32 位机器,整个页表有多大?
- php - 强制当前目录中的错误日志文件
- spring-boot - 无法使用带有 Spring Boot 的 jasypt 解密错误
- swift - 如何删除 SnapShot 侦听器(Firestore - Swift)
- modelica - 如何在绘制结果期间在 dymola 中设置多个垂直轴?
- node.js - Mocha 和 Chai 与 NodeJS,简单的服务器测试失败,404(应该是 200)