[R] TRUE/FALSE as numeric values

Gavin Simpson gavin.simpson at ucl.ac.uk
Fri Feb 23 14:55:24 CET 2007


On Fri, 2007-02-23 at 14:38 +0100, Thomas Preuth wrote:
> Hello,
> 
> I want to select in a column of a dataframe all numbers smaller than a 
> value x
> but when I type in test<-(RSF_EU$AREA<=x) I receiv as answer:
>  > test
>  [1]  TRUE FALSE FALSE  TRUE  TRUE  TRUE FALSE FALSE  TRUE  TRUE  TRUE 
> FALSE  TRUE  TRUE  TRUE  TRUE  TRUE
> [18]  TRUE  TRUE  TRUE  TRUE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  
> TRUE  TRUE FALSE  TRUE  TRUE  TRUE
> [35] FALSE  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE  TRUE  TRUE FALSE  
> TRUE  TRUE FALSE FALSE  TRUE FALSE
> [52]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE FALSE  TRUE
> 
> How can i get the values smaller than x and not the TRUE/FALSE reply?
> 
> Thanks in advance,
> Thomas

You need to subset your object based on the results you achieved above.
What you did was only half the job. See this example, with a number of
ways to get what you want:

## some dummy data to work with
dat <- 10 * runif(100)
dat <- data.frame(AREA = dat, FOO = dat + rnorm(100))

## select values of AREA less than mean AREA
mn <- mean(dat$AREA)
want1 <- with(dat, AREA[AREA <= mn])
## or
want2 <- dat$AREA[dat$AREA <= mn]
## or
want3 <- subset(dat$AREA, dat$AREA <= mn)
## or
want4 <- subset(dat, AREA <= mn)$AREA
## check they all do same thing
all.equal(want1, want2, want3, want4) ## TRUE

want2 is closest to how you tried to do it:

dat$AREA[dat$AREA <= mn]
         ^^^^^^^^^^^^^^
Notice that you only did the inner bit marked, which as you found
returns TRUE/FALSE depending on whether that element of AREA met the
criterion of being less than or equal to your x. This information is
used to select elements from AREA using the subsetting functions for
objects.

HTH

G
-- 
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
 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