[R] unexpected subset select results?

Gavin Simpson gavin.simpson at ucl.ac.uk
Tue Aug 24 09:55:22 CEST 2010


On Mon, 2010-08-23 at 17:51 -0400, ivo welch wrote:
> quizz---what does this produce?

Henrique has provided an answer to the question, but...

>    d=data.frame( a=1:1000, b=2001:3000, z= 5001:6000 )
>    attach(d); c <- (a+b)>25; detach(d)

...this is ugly and will potentially catch you out one day if you forget
to detach. These three calls can be achieved using a single with() :

c <- with(d, (a + b) > 25)

And the version you wanted:

attach(d); d$c <- (a+b)>25; detach(d)

can be done using within():

d <- within(d, c <- (a + b) > 25)

and with the latter, the intention is pretty clear.

HTH

G

>    d= subset(d, TRUE, select=c( a, b, c ))
> 
> yes, I know I have made a mistake, in that the code does not do what I
> presumably would have wanted.  it does seem like unexpected behavior,
> though, without an error.  there probably is some reason why this does
> not ring an alarm bell...
> 
> /iaw
> ----
> Ivo Welch (ivo.welch at brown.edu, ivo.welch at gmail.com)
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

-- 
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
 Dr. Gavin Simpson             [t] +44 (0)20 7679 0522
 ECRC, UCL Geography,          [f] +44 (0)20 7679 0565
 Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
 Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
 UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%



More information about the R-help mailing list