myloginid
myloginid

Reputation: 1473

R - Select Elements from list that meet the criteria

I had a tough time selecting elements from a list that meet a function. So documenting the same with a solution.

check.digits <- function(x){ grepl('^(\\d+)$' , x) }

x = "741 abc pqr street 71 15 41 510741"
lx = strsplit(x, split = " ", fixed = TRUE)
lapply(lx, check.digits)

This does not work -

lx[[1]][c(lapply(lx, check.digits))]

Use -

lx[[1]][sapply(lx, check.digits)]

thanks!!!

Upvotes: 1

Views: 1039

Answers (2)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

Given what you're after, perhaps you should just use gregexpr + regmatches:

regmatches(x, gregexpr("\\d+", x))
# [[1]]
# [1] "741"    "71"     "15"     "41"     "510741"

Or, from "qdapRegex", use rm_number:

library(qdapRegex)
rm_number(x, extract = TRUE)
# [[1]]
# [1] "741"    "71"     "15"     "41"     "510741"

Or, from "stringi", use stri_extract_all_regex:

library(stringi)
stri_extract_all_regex(x, "\\d+")
# [[1]]
# [1] "741"    "71"     "15"     "41"     "510741"

Add an [[1]] at the end if you're just dealing with a single string and are just interested in the single vector.

Upvotes: 3

myloginid
myloginid

Reputation: 1473

Use

lx[[1]][sapply(lx, check.digits)]
[1] "741"    "71"     "15"     "41"     "510741"

Upvotes: 1

Related Questions