测试数字是否在R中的字符串中

test if number is in string in R

我有以下df

df <-
    a    b  c
    20  10 20€
    20€ 10 20 Euro

我想测试数字 20 是否是字段的一部分。因此,结果应如下所示:

[1]true [2]false [3]true
[4]true [5]false [6]true

我试过了

grepl(df[3,3], 20)
grepl(df[3,3], "20")

两者都 return 错误。

你说你想要一个类似矩阵的逻辑视图。布赖恩的评论是正确的,模式是第一位的......但你还需要考虑结构:grepl(ptn, some_data_frame) returns 一个向量(看起来像一个 "all-or-nothing" 每列),而 grepl(ptn, some_matrix) returns 矩阵中每个元素的逻辑......尽管尺寸不正确,但可更正。

`dim<-`(grepl("20", as.matrix(df)), dim(df))
#      [,1]  [,2] [,3]
# [1,] TRUE FALSE TRUE
# [2,] TRUE FALSE TRUE

### or, more eye-friendly
out <- grepl("20", as.matrix(df))
dim(out) <- dim(df)
out
#      [,1]  [,2] [,3]
# [1,] TRUE FALSE TRUE
# [2,] TRUE FALSE TRUE

顺便说一句:如果您正在寻找 任何包括“20” 的数字,包括 120 和 200,那么这很好。如果您想要的字段中唯一的数字部分是“20”(既不是 120 也不是 200 计数),那么您需要 "\b20\b" 作为您的模式。 (感谢安德鲁。)


数据:

df <- read.table(header=T, text="
    a    b  c
    20  10 20€
    20€ 10 20Euro")

顺便说一句:grepl("20", df) returns 长度为 3 的向量(每列一个)的原因是它在内部将对象转换为字符。这解释了为什么你只得到三个:

as.character(df)
# [1] "c(20, 20)" "c(10, 10)" "1:2"      

您可以在此处选择使用 Vectorize 功能,也可以 purrr::map_dfr

Vectorize(grepl, vectorize.args = 'x')(pattern='20', df)
purrr::map_dfr(df, ~grepl('20', .x))

但我的解决方案并不比上面的好(@r2evans 更优雅),如果你想严格匹配 20,那么你也可以使用边界条件 \b20\b 而不是 20.

数据:

structure(list(a = c("20", "20€"), b = c("10", "10"), c = c("20€", 
"2 Euro")), class = "data.frame", row.names = c(NA, -2L))

输出:

Vectorize(grepl, vectorize.args = 'x')(pattern='20', df)
        a     b     c
[1,] TRUE FALSE  TRUE
[2,] TRUE FALSE  TRUE