On Wed, 16 Feb 2005 10:00:01 +0000, Robin Hankin <[EMAIL PROTECTED]> 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? I think it might be. Think of a situation where make.real is almost never all true. Then z would almost always remain complex after z[make.real] <- Re(z[make.real]) but on rare occasions would switch to being real. If some poor programmer assumed that z was always complex, it would likely pass tests, but on rare occasions would give garbage. (Off the top of my head I can't think of any cases where R code that expects a complex vector would fail if passed a real one, but it's certainly easy to construct cases in external code.) I think it's safer to make the conversion explicitly if you happen to know that all(make.real) is true. Duncan Murdoch ______________________________________________ R-help@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