Exploring Data Frames with Boolean Selection in R

Introduction

Welcome, dear learners! Today's focus is on mastering one of R's key skills — Boolean selection. This powerful tool in the data manipulation toolbox allows us to filter data, facilitating refined and targeted data wrangling.

Understanding Boolean Selection

Let's dissect what we mean by Boolean selection. In R, data frame elements are typically selected through their index values. However, when you wish to filter rows based on conditions, the significance of Boolean selection shines through.

A Boolean vector, comprised of TRUE or FALSE values, determines which rows from a data frame we select. As you may have already guessed, these vectors are brought to life through logical operations on our data.

Consider this elementary example: finding numbers greater than 5 in a vector. Here's how you would accomplish it:

R
# Vector of numbers
numbers <- c(2, 5, 7, 10)

# Boolean vector for numbers > 5
numbers_more_than_five <- numbers > 5

# Print the Boolean vector
print(numbers_more_than_five) # [1] FALSE FALSE  TRUE  TRUE

After running this code, we obtain a Boolean vector that indicates which values from numbers exceed 5.

Applying Boolean Selection to R Data Frames: Dataset

Let's expand this concept with a practical scenario provided by the mtcars dataset. Let's print it:

R
print(mtcars)
text
                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
...

Applying Boolean Selection to R Data Frames: Example

Our task is to identify the cars that offer more than 20 MPG (miles per gallon) and have 6 or less cylinders. Here's how we can execute this operation:

R
# Boolean vector for cars with mpg > 20 and cyl <= 6
high_mpg_low_cyl_cars <- mtcars$mpg > 20 & mtcars$cyl <= 6

# Filter the mtcars data frame
mtcars_filtered <- mtcars[high_mpg_low_cyl_cars,]

# Print the filtered data frame
print(mtcars_filtered) 

Voilà! We have successfully filtered the mtcars data frame.

text
                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4      21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710     22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive 21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
...
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal