根据次数重新排序多项式列名称

问题描述 投票:0回答:1

我正在尝试使用

poly
中的
R
函数进行扩展后重新排序列名称。

我写的初始函数如下所示:

> 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"

我现在尝试将变量名称更改为 x1 x2 和 x3。然而,我希望将代码概括为允许超过 3 个变量。我还想更新它以使用

^
来获得如下功能:

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"  

如何编辑第二个

sapply
以与第一个
sapply
相同的方式对列进行排序?

提前致谢。

r sapply
1个回答
0
投票

我觉得你几乎就是外面的

rev
,但只是缺少
seq_along(powers)

你可以试试

s <- strsplit(substring(colnames(sorted_data), 2), "\\.")
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) # <------ here is the minor change

    # Filter out any NULL values from the terms list
    terms <- Filter(Negate(is.null), terms)

    # Collapse the terms into one string
    paste(terms, collapse = "")
})

你将获得

> sorted_data_test
        x1       x2     x1^2    x2x1     x2^2     x1^3   x2x1^2   x2^2x1
1 1.701692 1.071616 2.895755 1.82356 1.148361 4.927683 3.103138 1.954156
2 1.720578 1.035489 2.960388 1.78164 1.072238 5.093578 3.065450 1.844869
      x2^3
1 1.230602
2 1.110291
© www.soinside.com 2019 - 2024. All rights reserved.