[R] Calculating the 2th power of a vector

Martin Maechler maechler at stat.math.ethz.ch
Tue Nov 29 17:38:06 CET 2005


>>>>> "BaRow" == Barry Rowlingson <B.Rowlingson at lancaster.ac.uk>
>>>>>     on Tue, 29 Nov 2005 16:30:11 +0000 writes:

    BaRow> Amir Safari wrote:
    >> I simply want to calculate the 2th power of a vector
    >> without changing the sign of values. How it is possible
    >> in R ?


    BaRow> I'm not quite sure what you mean, but maybe:

    >> x
    BaRow>   [1] -4 -3 -2 -1 0 1 2 3 4
    >> x^2
    BaRow>   [1] 16 9 4 1 0 1 4 9 16

    BaRow>   - that obviously makes everything positive (unless
    BaRow> any of x are complex!)

    BaRow>   So do:

    >> x^2 * sign(x)
    BaRow>   [1] -16 -9 -4 -1 0 1 4 9 16


    BaRow>   to keep the sign. Is that what you want?

which is
           x * abs(x)

{of course, the are more possibilities -- since the OP asked "how" .. ;-)
 but I'd guess that  x*abs(x) is close to speed-optimal}

Martin Maechler, ETH Zurich




More information about the R-help mailing list