backtransform `scale()` for plotting

前端 未结 8 2250
别那么骄傲
别那么骄傲 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:45

    Take a look at:

    attributes(d$s.x)
    

    You can use the attributes to unscale:

    d$s.x * attr(d$s.x, 'scaled:scale') + attr(d$s.x, 'scaled:center')
    

    For example:

    > x <- 1:10
    > s.x <- scale(x)
    
    > s.x
                [,1]
     [1,] -1.4863011
     [2,] -1.1560120
     [3,] -0.8257228
     [4,] -0.4954337
     [5,] -0.1651446
     [6,]  0.1651446
     [7,]  0.4954337
     [8,]  0.8257228
     [9,]  1.1560120
    [10,]  1.4863011
    attr(,"scaled:center")
    [1] 5.5
    attr(,"scaled:scale")
    [1] 3.02765
    
    > s.x * attr(s.x, 'scaled:scale') + attr(s.x, 'scaled:center')
          [,1]
     [1,]    1
     [2,]    2
     [3,]    3
     [4,]    4
     [5,]    5
     [6,]    6
     [7,]    7
     [8,]    8
     [9,]    9
    [10,]   10
    attr(,"scaled:center")
    [1] 5.5
    attr(,"scaled:scale")
    [1] 3.02765
    
    0 讨论(0)
  • 2020-11-28 07:46

    I came across this problem and I think I found a simpler solution using linear algebra.

    # create matrix like object
    a <- rnorm(1000,5,2)
    b <- rnorm(1000,7,5) 
    
    df <- cbind(a,b)
    
    # get center and scaling values 
    mean <- apply(df, 2, mean)
    sd <- apply(df, 2, sd)
    
    # scale data
    s.df <- scale(df, center = mean, scale = sd)
    
    #unscale data with linear algebra 
    us.df <- t((t(s.df) * sd) + mean)
    
    0 讨论(0)
提交回复
热议问题