0
0
R Programmingprogramming~20 mins

grep and grepl in R Programming - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
grep and grepl Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of grep with value = TRUE
What is the output of this R code?
vec <- c("apple", "banana", "cherry", "date")
grep("a", vec, value = TRUE)
R Programming
vec <- c("apple", "banana", "cherry", "date")
grep("a", vec, value = TRUE)
A[1] "apple" "banana" "date"
B[1] 1 2 4
C[1] "apple" "banana" "cherry" "date"
D[1] 1 2 3 4
Attempts:
2 left
💡 Hint
Remember, value = TRUE returns the matching elements, not their positions.
Predict Output
intermediate
2:00remaining
Output of grepl with logical vector
What is the output of this R code?
vec <- c("cat", "dog", "bird", "cow")
grepl("o", vec)
R Programming
vec <- c("cat", "dog", "bird", "cow")
grepl("o", vec)
A[1] FALSE FALSE FALSE TRUE
B[1] TRUE TRUE FALSE TRUE
C[1] TRUE FALSE FALSE TRUE
D[1] FALSE TRUE FALSE TRUE
Attempts:
2 left
💡 Hint
grepl returns TRUE for elements containing the pattern, FALSE otherwise.
🧠 Conceptual
advanced
2:00remaining
Difference between grep and grepl
Which statement correctly describes the difference between grep() and grepl() in R?
Agrep() returns the count of matches; grepl() returns the matching strings.
BBoth grep() and grepl() return matching values but in different orders.
Cgrep() returns indices or matching values; grepl() returns a logical vector indicating matches.
Dgrep() returns a logical vector; grepl() returns indices of matches.
Attempts:
2 left
💡 Hint
Think about what each function returns: positions vs logical flags.
Predict Output
advanced
2:00remaining
Output of grep with fixed = TRUE
What is the output of this R code?
vec <- c("a.c", "abc", "a-c", "a.c")
grep("a.c", vec, fixed = TRUE)
R Programming
vec <- c("a.c", "abc", "a-c", "a.c")
grep("a.c", vec, fixed = TRUE)
A[1] 1 4
B[1] 1 2 4
C[1] 1 3 4
D[1] 2 3
Attempts:
2 left
💡 Hint
fixed = TRUE treats the pattern as a plain string, not a regular expression.
Predict Output
expert
2:00remaining
Count of matches using grepl and sum
What is the value of count after running this R code?
vec <- c("red", "green", "blue", "yellow", "redgreen")
count <- sum(grepl("red", vec))
count
R Programming
vec <- c("red", "green", "blue", "yellow", "redgreen")
count <- sum(grepl("red", vec))
count
A4
B2
C1
D3
Attempts:
2 left
💡 Hint
grepl returns TRUE for each element containing "red"; sum counts TRUE as 1.