backtransform `scale()` for plotting

前端 未结 8 2248
别那么骄傲
别那么骄傲 2020-11-28 07:05

I have a explanatory variable that is centered using scale() that is used to predict a response variable:

d <- data.frame(
  x=runif(100),
           


        
8条回答
  •  一生所求
    2020-11-28 07:44

    For a data frame or matrix:

    set.seed(1)
    x = matrix(sample(1:12), ncol= 3)
    xs = scale(x, center = TRUE, scale = TRUE)
    
    x.orig = t(apply(xs, 1, function(r)r*attr(xs,'scaled:scale') + attr(xs, 'scaled:center')))
    
    print(x)
         [,1] [,2] [,3]
    [1,]    4    2    3
    [2,]    5    7    1
    [3,]    6   10   11
    [4,]    9   12    8
    
    print(x.orig)
         [,1] [,2] [,3]
    [1,]    4    2    3
    [2,]    5    7    1
    [3,]    6   10   11
    [4,]    9   12    8
    

    Be careful when using functions like identical():

    print(x - x.orig)
         [,1] [,2]         [,3]
    [1,]    0    0 0.000000e+00
    [2,]    0    0 8.881784e-16
    [3,]    0    0 0.000000e+00
    [4,]    0    0 0.000000e+00
    
    identical(x, x.orig)
    # FALSE
    

提交回复
热议问题