如何在由数字和字母构成的字符值列中找到一个数值字符?

问题描述 投票:0回答:1

假设我有一个数据框如下(但更大)

df = data.frame(x = c('1E','2E',3,4,5) )

我希望能够找到没有字母的字符 3,4 和 5 的行号。感谢帮助。

r regex dataframe character numeric
1个回答
0
投票

我们可以使用

grepl()
并查找
3
4
5
,并且只查找以
^
和以
$
结尾的行:

library(dplyr)

df = data.frame(x = c('1E','2E',3,4,5) )

df %>% filter(grepl(paste0("^(",paste(3:5, collapse = "|"), ")$"), x))
#>   x
#> 1 3
#> 2 4
#> 3 5

如果你有多个列,你可以使用

if_any
来搜索这些字符串的所有字符列:

df %>% filter(if_any(where(is.character),
                     ~ grepl(paste0("^(",paste(3:5, collapse = "|"), ")$"), .x)))

reprex 包 (v2.0.1) 于 2023-02-21 创建

© www.soinside.com 2019 - 2024. All rights reserved.