R - Select 列表中满足条件的元素
R - Select Elements from list that meet the criteria
我很难从列表中选择满足某个功能的元素。所以用解决方案记录相同的内容。
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)]
谢谢!!!
使用
lx[[1]][sapply(lx, check.digits)]
[1] "741" "71" "15" "41" "510741"
考虑到您的需求,也许您应该使用 gregexpr
+ regmatches
:
regmatches(x, gregexpr("\d+", x))
# [[1]]
# [1] "741" "71" "15" "41" "510741"
或者,从 "qdapRegex" 开始,使用 rm_number
:
library(qdapRegex)
rm_number(x, extract = TRUE)
# [[1]]
# [1] "741" "71" "15" "41" "510741"
或者,从 "stringi" 开始,使用 stri_extract_all_regex
:
library(stringi)
stri_extract_all_regex(x, "\d+")
# [[1]]
# [1] "741" "71" "15" "41" "510741"
如果您只是处理单个字符串并且只对单个向量感兴趣,请在末尾添加一个 [[1]]
。
我很难从列表中选择满足某个功能的元素。所以用解决方案记录相同的内容。
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)]
谢谢!!!
使用
lx[[1]][sapply(lx, check.digits)]
[1] "741" "71" "15" "41" "510741"
考虑到您的需求,也许您应该使用 gregexpr
+ regmatches
:
regmatches(x, gregexpr("\d+", x))
# [[1]]
# [1] "741" "71" "15" "41" "510741"
或者,从 "qdapRegex" 开始,使用 rm_number
:
library(qdapRegex)
rm_number(x, extract = TRUE)
# [[1]]
# [1] "741" "71" "15" "41" "510741"
或者,从 "stringi" 开始,使用 stri_extract_all_regex
:
library(stringi)
stri_extract_all_regex(x, "\d+")
# [[1]]
# [1] "741" "71" "15" "41" "510741"
如果您只是处理单个字符串并且只对单个向量感兴趣,请在末尾添加一个 [[1]]
。