本文介绍了R-从列表中选择符合条件的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难从列表中选择满足功能的元素.因此,用解决方案将其记录下来.

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)

这不起作用-

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

使用-

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

谢谢!

推荐答案

给出您想要的内容,也许您应该只使用gregexpr + regmatches:

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

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

或者,从"qdapRegex"中,使用rm_number:

Or, from "qdapRegex", use rm_number:

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

或者,从字符串"中使用stri_extract_all_regex:

Or, from "stringi", use stri_extract_all_regex:

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

如果您只处理单个字符串,并且只对单个向量感兴趣,请在末尾添加[[1]].

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

这篇关于R-从列表中选择符合条件的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 00:40