我有一个包含4列的data.frame,我想scale
,然后添加一些新列(不缩放它们(。然后我执行一些计算,之后我只需要unscale
前4列(因为剩下的两列一开始没有缩放(。DMwR::unscale
似乎允许col.ids
的论点。但当我指定下面这样的函数时,它会返回
DMwR::unscale中的错误(cbind(scale(x(,x2(,scale(x(,1:4(:要取消缩放的数据维度不正确。
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