Introduction
Logical indexing helps you pick elements from a list or vector by using TRUE or FALSE values. It is like choosing items based on yes/no questions.
vector[logical_vector]
x <- c(5, 12, 8, 20) x[x > 10]
names <- c("Anna", "Bob", "Amy") names[substr(names, 1, 1) == "A"]
v <- c(1, 2, 3, 4, 5) v[c(TRUE, FALSE, TRUE, FALSE, TRUE)]
numbers <- c(3, 15, 7, 22, 9) # Select numbers greater than 10 big_numbers <- numbers[numbers > 10] print(big_numbers)
v[c(TRUE, FALSE, TRUE)]?vv where the index is TRUE -> Option Ax where values are greater than 5 using logical indexing?x > 5 creates a logical vector TRUE where elements are greater than 5.xx[x > 5] selects elements of x where the condition is TRUE.x[> 5]v <- c(10, 3, 7, 2, 9) v[v >= 7]
v >= 7nums <- c(4, 8, 15, 16, 23, 42) nums[nums > 10 & TRUE]
nums > 10 & TRUEnums > 10 returns a logical vector; AND with TRUE keeps it unchanged.nums, and syntax is correct, so no error occurs.temps <- c(23, NA, 19, 25, NA, 21), how can you use logical indexing to select only the non-missing values?is.na(temps) returns TRUE for missing values (NA) and FALSE otherwise.!is.na(temps) creates a logical vector TRUE where values are not missing.temps with this logical vectortemps.Pass the test and this pattern moves unknown