my_vec <- c(-10, -20, 30, 10, 50, 40, -100)
beers <- c("BUD LIGHT", "BUSCH LIGHT", "COORS LIGHT",
"GENESEE LIGHT", "MILLER LITE", "NATURAL LIGHT")Classwork 4
Filtering a Vector
Question 1.
- Consider the vectors:
- Write an R code to filter only the positive values in
my_vec. - Use positional indexing to keep the beer names in positions 2, 4, and 6.
Answer:
Use a logical condition inside square brackets to select the positive numbers. For the beer names, supply the positions to keep as a numeric vector.
positive_values <- my_vec[my_vec > 0]
positive_values[1] 30 10 50 40
selected_beers <- beers[c(2, 4, 6)]
selected_beers[1] "BUSCH LIGHT" "GENESEE LIGHT" "NATURAL LIGHT"
my_vec > 0 checks each number and returns TRUE only for positive values, so positive_values is c(30, 10, 50, 40). The number 0 would be excluded because it is not positive. R counts positions starting at 1; positions 2, 4, and 6 give c("BUSCH LIGHT", "GENESEE LIGHT", "NATURAL LIGHT"), in that order.
Question 2.
- Create a logical vector
logical_vecthat checks whether the elements of the vectorages <- c(15, 22, 18, 24, 30)are greater than or equal to 20. - Use
logical_vecinside square brackets to keep only the ages that are greater than or equal to 20.
ages <- c(15, 22, 18, 24, 30)Answer:
First compare every age with 20. Save the resulting TRUE and FALSE values, then use them to index ages.
logical_vec <- ages >= 20
logical_vec[1] FALSE TRUE FALSE TRUE TRUE
ages_20_or_older <- ages[logical_vec]
ages_20_or_older[1] 22 24 30
logical_vec is c(FALSE, TRUE, FALSE, TRUE, TRUE): 15 and 18 are below 20, while 22, 24, and 30 meet the condition. Inside square brackets, TRUE keeps an element and FALSE drops it. Therefore ages[logical_vec] returns c(22, 24, 30) in the original order. The >= operator includes age 20 itself, if it appears in the vector.
