Complete the code to find the indices of elements containing the letter 'a'.
words <- c("apple", "banana", "cherry", "date") indices <- grep([1], words) print(indices)
The grep function returns the indices of elements that match the pattern. Here, we look for the letter 'a'.
Complete the code to check which elements contain the letter 'e' and return TRUE or FALSE.
words <- c("apple", "banana", "cherry", "date") contains_e <- grepl([1], words) print(contains_e)
grep instead of grepl when expecting TRUE/FALSE.The grepl function returns a logical vector indicating if the pattern is found in each element. Here, we check for 'e'.
Fix the error in the code to correctly find words containing 'n'.
words <- c("apple", "banana", "cherry", "date") result <- grep([1], words, value = TRUE) print(result)
The pattern must be a string in quotes. Without quotes, R treats it as a variable, causing an error.
Fill both blanks to create a named logical vector showing which words contain 'a'.
words <- c("apple", "banana", "cherry", "date") result <- setNames(grepl([1], words), [2]) print(result)
grepl checks for 'a' in each word. setNames assigns the original words as names to the logical vector.
Fill all three blanks to create a named vector of words containing 'e' with their indices.
words <- c("apple", "banana", "cherry", "date") indices <- grep([1], words) selected_words <- words[[2]] named_vector <- setNames(selected_words, [3]) print(named_vector)
We search for 'e' with grep, get indices, select words at those indices, and name them with the same indices.