planets_df
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
planets_df[rings_vector,]
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?
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.
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.
i <- c(TRUE, FALSE, TRUE)
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