[R] Inverting a scale(X)

Peter Ehlers ehlers at ucalgary.ca
Thu Jul 8 09:37:10 CEST 2010


On 2010-07-07 19:19, Godfrey van der Linden wrote:
>
> On 2010-07-03, at 17:43 , Peter Ehlers wrote:
>
>>
>> On 2010-07-03 0:05, Godfrey van der Linden wrote:
>>> G'day, All.
>>>
>>> I have been trying to trackdown a problem in my R analysis script. I perform a scale() operation on a matrix then do further work.
>>>
>>> Is there any way of inverting the scale() such that
>>>      sX<- scale(X)
>>>      Xprime<- inv.scale(x); 	# does inv.scale exist?
>>>
>>> resulting in Xprime_{ij} == X_{ij} where Xprime_{ij} \in R
>>>
>>> There must be some way of doing it but I'm such a newb that I haven't been able to find it.
>>>
>>> Thanks
>>>
>>> Godfrey
>>>
>>
>> If your sX hasn't lost the "scaled:center" and
>> "scaled:scale" attributes that it got from the
>> scale() operation, then you can just reverse
>> the scaling procedure using those. Multiply
>> columns by the "scale" attribute, then add the
>> "center" attribute. Something like:
>>
>> MN<- attr(sx, "scaled:center")
>> SD<- attr(sx, "scaled:scale")
>> Xprime<- t(apply(sx, 1, function(x){x * SD + MN}))
>>
>> If the attributes have been lost by your further
>> work, then I'm afraid you're out of luck.
>>
>>   -Peter Ehlers
>
> Thanks for this, I had forgotten the transpose function existed. I did maintain the attributes, though I was surprised how many times I had to move them manually in my script.
>
> Anyway I also tried a functional programming solution and I'm sort of curious what the differences are? I used rep to build out the SD and MN vectors. Something like this (though I have lost the precise code now and would have to regenerate it)
>
> nr = nrow(sx)
> Xprime = sx * rep(SD, each=nr) + rep(MN, each=nr);
>
> Is there any way of determining which approach is more efficient?

Presumably by 'more efficient' you mean faster.
You can check with system.time() on a sufficiently
large matrix (1000-by-1000, say). Since the apply()
method loops over rows, it will be somewhat slower.
Also, your vector calculation will retain the
attributes of sx.

   -Peter Ehlers

>
> Thanks again.
>
> Godfrey
>
>



More information about the R-help mailing list