[R] real and complex vectors

Uwe Ligges ligges at statistik.uni-dortmund.de
Wed Feb 16 11:33:51 CET 2005


Robin Hankin wrote:

> The following caught me off-guard:
> 
> 
> R> z <- 1i + 1:10
> R> z <- Re(z)
> R> z
>  [1]  1  2  3  4  5  6  7  8  9 10
> 
> as expected.  But look:
> 
> R> z <- 1i + 1:10
> R> make.real <- abs(z) < 1000
> R> z[make.real] <- Re(z[make.real])
> R> z
>  [1]  1+0i  2+0i  3+0i  4+0i  5+0i  6+0i  7+0i  8+0i  9+0i 10+0i
> R>
> 
> didn't make z a real vector, which is what I wanted.  ?"[<-" says
> 
>      If one of these expressions appears on the left side of an
>      assignment then that part of 'x' is set to the value of the right
>      hand side of the assignment.
> 
> so the behaviour is as documented: class(z) is unchanged in the second 
> session.
> 
> Would modifying "[<-" to add a test for all elements of an object being 
> replaced (and
> if this is the case  to change the class of z appropriately),  be a bad 
> idea?

Sorry, but yes, a bad idea.

If you use

  z[someIndex] <- someValues

you expect that z only changes its class if required to represent 
"someValues", but never vice versa.
That's in particular TRUE for the case of explicitly indexing all 
elements as in:

  z <- 1i + 1:10
  z[] <- 1:10

And why should R do different things in the following two cases, comparing
   z[1:5] <- 1:5
and
   z[1:10] <- 1:10
?


Uwe Ligges



> 
> -- 
> Robin Hankin
> Uncertainty Analyst
> Southampton Oceanography Centre
> European Way, Southampton SO14 3ZH, UK
>  tel  023-8059-7743
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! 
> http://www.R-project.org/posting-guide.html




More information about the R-help mailing list