部分字符串完全匹配

时间:2016-10-13 04:53:33

标签: r data-manipulation grepl

我已经搜索了很多但是找不到解决方案......我想对于你们中的许多人来说这很容易......但不适合我。

 df <- data.frame(site = c("11", " 4 , 111", "3,1 ", "4,11111 "))
> df
      site
1       11
2  4 , 111
3     3,1 
4 4,11111

我有一个列,其中多个站点代码可能用逗号分隔(不是可能出现的随机空格)。我正在尝试查找与感兴趣的字符串站点编号匹配的行。

搜索网站为11或3'c(1,3)'匹配的行的结果应返回:

[1] 1 0 1 0

我似乎无法解决这个问题......我猜答案会包括

temp <- strsplit(df$site, ",")

,但我似乎无法理解如何在该步骤之后在列表上应用函数...我会做一个

grepl(c("^11$", "^3$"), temp)

但这不起作用。

3 个答案:

答案 0 :(得分:3)

由于您正在寻找完全匹配而不是模式匹配,因此您可以尝试:

df <- data.frame(site = c("11", " 4 , 111", "3,1 ", "4,11111 "), stringsAsFactors = FALSE)
as.integer(unlist(lapply(strsplit(df$site, split=","), function(x) any(x == 3 | x == 11))))

[1] 1 0 1 0

答案 1 :(得分:2)

您可以尝试使用sapply

as.integer(sapply(df$site,function(x)grepl("^11|^3",x)))

[1] 1 0 1 0

答案 2 :(得分:1)

我们可以做一个grep

+(grepl("\\b(3|11)\\b", df$site))
#[1] 1 0 1 0
相关问题