[R] Why does R do this?

Duncan Murdoch murdoch@dunc@n @ending from gm@il@com
Tue Jan 8 12:54:43 CET 2019


On 08/01/2019 4:28 a.m., Nick Wray via R-help wrote:
> y<-c(1,2,3)
> z<-which(y>3)

At this point z is a vector with no entries in it.

> z
> y<-y[-z]

-z is the same vector.  So y[z] and y[-z] are the same.

> y
> 
> In the work I'm doing I often have this situation and have to make sure that I condition on z being non-zero as y is now numeric(0) rather than the set c(1,2,3).  Why does R do this?  Wouldn't it be more sensible for R to simply leave the host set unchanged if there are no elements to take out?

No, it wouldn't.  You asked for no entries, so you get no entries.

Follow Thierry's advice, and don't use which() unless you really need a 
vector of indices, and are prepared for an empty one.

Duncan Murdoch



More information about the R-help mailing list