问题
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!!!
回答1:
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.
回答2:
Use
lx[[1]][sapply(lx, check.digits)]
[1] "741" "71" "15" "41" "510741"
来源:https://stackoverflow.com/questions/33930333/r-select-elements-from-list-that-meet-the-criteria