[R] Calculating the 2th power of a vector

Barry Rowlingson B.Rowlingson at lancaster.ac.uk
Tue Nov 29 17:30:11 CET 2005


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 ?


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

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

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

  So do:

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

  to keep the sign. Is that what you want?

Baz




More information about the R-help mailing list