R - Select Elements from list that meet the criteria

偶尔善良 提交于 2019-12-08 03:33:11

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!