Skip to content

How to get values from dataframe's column conditional on other column

6 messages · Yuri Volchik, Dirk Eddelbuettel, Gabor Grothendieck +1 more

#
Hi to all members of this list,

I'm quite a novice to R and was wondering if there is a more elegant
way to solve a following problem:
Suppose we have a dataframe
  X     Y
.12   TRUE
-.24  TRUE
..     ...
.34   FALSE

i.e. two (or more columns) with data and we want to get vector of X
values conditional on Y values (say only X's when Y=TRUE).
Of course it is possible to do it by looping through the whole
dataframe, i was wondering if there is a a more elegant solution to
this in R?
#
On Tue, Jun 13, 2006 at 12:35:36PM +0100, Yuri Volchik wrote:
You would do yourself a huge favour if you read the 'An Introduction to R'
manual distributed with R, or, for that matter, any of the other contributed  
introductory manuals on the R/CRAN site.

The answer, by the way, is 

    DF[ DF[,"Y"]==TRUE, "X" ]

ie you create a boolean condution for the rows (and == 'TRUE' could be
omitted if Y is boolean), and then select "X".  There are still issues that
may confuse you about data.frames collapsing to a single vector, please go
and read the manual. Really.

Dirk
#
If DF is your data.frame

with(DF, X[Y])

or

DF$X[DF$Y]
On 6/13/06, Yuri Volchik <volchik2000 at list.ru> wrote:
#
Sorry, that should be:

with(DF, X[Y,])

or

DF[DF$Y, "X"]
On 6/13/06, Gabor Grothendieck <ggrothendieck at gmail.com> wrote:
#
Aaarg.  Here it is again.  Hopefully I got it right this time.  Three
possibilities are:
[1] 1 2
[1] 1 2
[1] 1 2
On 6/13/06, Gabor Grothendieck <ggrothendieck at gmail.com> wrote:
#
There's more than one way to do it.  My favorite:

df <- data.frame(X = c(0.12, -0.24, 0.34),
                  Y = c(TRUE, TRUE, FALSE))

subset(df, Y, X)