ask a dataframe with a logical variable?

     name               type diameter rotation rings
1 Mercury Terrestrial planet    0.382    58.64 FALSE
2   Venus Terrestrial planet    0.949  -243.02 FALSE
3   Earth Terrestrial planet    1.000     1.00 FALSE
4    Mars Terrestrial planet    0.532     1.03 FALSE
5 Jupiter          Gas giant   11.209     0.41  TRUE
6  Saturn          Gas giant    9.449     0.43  TRUE
7  Uranus          Gas giant    4.007    -0.72  TRUE
8 Neptune          Gas giant    3.883     0.67  TRUE

rings_vector <- planets_df$rings

# to use rings_vector to select the data for the four planets with rings

I feel surprised that the above command just gives me the desired output. Here it seems R automatically filter "TRUE" value of "rings_vector". Can anyone help me explain it?

What's your problem? You just tell the data frame which rows you want to keep and which ones you want to throw away

Paraphrasing documentation for ?Extract: For objects such as
matrices, or data.frames x[i, j] that are indexed by rows i and columns j,
you can extract elements by passing \textbf i or \textbf j as logical vectors or expressions that evaluate as a logical vectors.

1 Like

Yes, I understand x[i,j] and x[i,].

But here is not i, instead it is rings_vector, a logical vector.I'm confused.

Hi Tung,
To tie together the help documentation and your example, \textbf i is a logical vector of which your rings_vector is the same class, and \textbf X is a matrix or data.frame of which planets_df is the same class. It doesn't matter so much what you name your objects but there are limits.

X <- data.frame(a = letters[1:3], b = letters[4:6])

X[i, ] # returns rows 1 and 3 corresponding where i is TRUE
#>   a b
#> 1 a d
#> 3 c f

apples <- c(TRUE, FALSE, TRUE)

X[apples, ]
#>   a b
#> 1 a d
#> 3 c f

Created on 2020-07-24 by the reprex package (v0.3.0)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.