You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于次数重排R中poly函数生成的多项式列名

问题

在R中使用poly函数扩展特征后,需要重命名列名。原代码生成x、y、xx这类列名,现在希望改为x1、x2的格式,并用^表示幂次,但修改后的代码生成的列名顺序与原代码不一致,需要调整。

初始代码及结果

> sorted_data
X0.1     X1.0     X0.2    X1.1     X2.0     X0.3     X1.2     X2.1     X3.0
1 1.701692 1.071616 2.895755 1.82356 1.148361 4.927683 3.103138 1.954156 1.230602
2 1.720578 1.035489 2.960388 1.78164 1.072238 5.093578 3.065450 1.844869 1.110291

s <- strsplit(substring(colnames(sorted_theta), 2), "\\.")
> s
[[1]]
[1] "0" "1"

[[2]]
[1] "1" "0"

[[3]]
[1] "0" "2"

[[4]]
[1] "1" "1"

[[5]]
[1] "2" "0"

colnames(sorted_data) <- sapply(s, function(x) {
      vec <- c("x", "y", "z")[seq_along(x)]
      x <- as.integer(x)
      y <- rep(vec, rev(x))
      paste(y, collapse = "")
    })

colnames(sorted_data)
[1] "x"   "y"   "xx"  "xy"  "yy"  "xxx" "xxy" "xyy" "yyy"

修改后的代码及问题

sorted_data_test <- sorted_data
colnames(sorted_data_test) <- sapply(s, function(powers) {
  terms <- mapply(function(power, index) {
    if (power == "0") {
      return(NULL)
    } else if (power == "1") {
      return(paste0("x", index))
    } else {
      return(paste0("x", index, "^", power))
    }
  }, powers, seq_along(powers), SIMPLIFY = FALSE)
  
  # Filter out any NULL values from the terms list
  terms <- Filter(Negate(is.null), terms)
  
  # Collapse the terms into one string
  paste(terms, collapse = "")
})

生成的列名:

print(colnames(sorted_theta_test))
[1] "x2"     "x1"     "x2^2"   "x1x2"   "x1^2"   "x2^3"   "x1x2^2" "x1^2x2" "x1^3"  

可以看到,修改后的列名顺序(x2、x1、x2^2...)和原代码的(x、y、xx...)逻辑对应但变量索引反转,导致顺序看起来不一致。

解决方案

问题根源在于原代码中使用了rev(x)反转了幂次的应用顺序,对应到变量索引上,需要将处理时的变量索引也反转。只需要修改mapply中的index参数,将seq_along(powers)改为rev(seq_along(powers))即可:

sorted_data_test <- sorted_data
colnames(sorted_data_test) <- sapply(s, function(powers) {
  terms <- mapply(function(power, index) {
    if (power == "0") {
      return(NULL)
    } else if (power == "1") {
      return(paste0("x", index))
    } else {
      return(paste0("x", index, "^", power))
    }
  }, powers, rev(seq_along(powers)), SIMPLIFY = FALSE)
  
  terms <- Filter(Negate(is.null), terms)
  paste(terms, collapse = "")
})

运行后生成的列名:

print(colnames(sorted_data_test))
[1] "x1"     "x2"     "x1^2"   "x1x2"   "x2^2"   "x1^3"   "x1^2x2" "x1x2^2" "x2^3"  

这个结果和原代码的列名顺序完全对应:x→x1、y→x2、xx→x1^2、xy→x1x2、yy→x2^2,以此类推。

内容的提问来源于stack exchange,提问作者AW27

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 01:40:56