tospig
tospig

Reputation: 8343

r - find list item where all values match a regular expression

Question

Given a list of vectors

lst
[[1]]
[1] "{{=Number}}"

[[2]]
[1] ""

[[3]]
[1] "Auto"   "Small"  "Medium" "Large" 

[[4]]
[1] "R1" "R2" "R3" "R4" "R5"

[[5]]
[1] "1" "2" "3" "4" "5"

How do I find the entry that consists of the set of R[0-9] combinations?

So in this exmample it will be lst[[4]]

some rules

Data

dput(lst)
list("{{=Number}}", "", c("Auto", "Small", "Medium", "Large"), 
     c("R1", "R2", "R3", "R4", "R5"), c("1", "2", "3", "4", "5"
     ))

Upvotes: 2

Views: 747

Answers (2)

Julius Vainora
Julius Vainora

Reputation: 48221

Another possibility:

sapply(lst, function(x) all(x %in% paste0("R", 0:9)))
# [1] FALSE FALSE FALSE  TRUE FALSE

Upvotes: 1

tospig
tospig

Reputation: 8343

@jenesaisquoi has provided a nice solution:

vapply(lst, function(x) all(grepl('^R[0-9]', x)), logical(1))

# [1] FALSE FALSE FALSE  TRUE FALSE

## e.g
# lst[vapply(lst, function(x) all(grepl('^R[0-9]', x)), logical(1))]
# [[1]]
# [1] "R1" "R2" "R3" "R4" "R5"

Upvotes: 1

Related Questions