DMwR::unscale 仅取消缩放选定的列

DMwR::unscale to unscale only selected columns

我有一个包含 4 列的 data.frame,我想 scale 然后添加一些新列(不缩放它们)。然后我执行一些计算,之后我只需要 unscale 前 4 列(因为其余两列一开始没有缩放)。 DMwR::unscale 似乎允许使用 col.ids 参数。但是当我像下面这样指定函数时 returns

Error in DMwR::unscale(cbind(scale(x), x2), scale(x), 1:4) : Incorrect dimension of data to unscale.

x <- matrix(2*rnorm(400) + 1, ncol = 4)
x2 <- matrix(9*rnorm(200), ncol = 2)
DMwR::unscale(cbind(scale(x), x2), scale(x), 1:4)

我做错了什么?我怎样才能取消缩放只选择矩阵的前 4 列?

DMwR::unscale(vals, norm.data, col.ids)函数要求norm.data的列数大于vals的列数。
我建议考虑 unscale 的以下修改版本:

myunscale <- function (vals, norm.data, col.ids)  {
    cols <- if (missing(col.ids)) 1:NCOL(vals) else col.ids
    if (length(cols) > NCOL(vals)) 
        stop("Incorrect dimension of data to unscale.")
    centers <- attr(norm.data, "scaled:center")[cols]
    scales <- attr(norm.data, "scaled:scale")[cols]
    unvals <- scale(vals[,cols], center = (-centers/scales), scale = 1/scales)
    unvals <- cbind(unvals,vals[,-cols])
    attr(unvals, "scaled:center") <- attr(unvals, "scaled:scale") <- NULL
    unvals
}

set.seed(1)
x <- matrix(2*rnorm(4000) + 1, ncol = 4)
x2 <- matrix(9*rnorm(2000), ncol = 2)
x_unsc <- myunscale(cbind(scale(x), x2), scale(x) , 1:4)

x_unsc的平均值和标准差为:

apply(x_unsc, 2, mean)
# [1]  0.9767037  0.9674762  1.0306181  1.0334445 -0.1805717 -0.1053083

apply(x_unsc, 2, sd)
# [1] 2.069832 2.079963 2.062214 2.077307 8.904343 8.810420