Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 部分字符串精确匹配_R_Data Manipulation_Grepl - Fatal编程技术网

R 部分字符串精确匹配

R 部分字符串精确匹配,r,data-manipulation,grepl,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 我似乎无法把这个弄出来。。。我想答案应该包括 temp <- strsplit(df$site, ",") 但这不起作用。因

我搜索了很多,但没有找到解决方案。。。我想对你们中的许多人来说,这是一个简单的问题。。。但对我来说不是

 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
我似乎无法把这个弄出来。。。我想答案应该包括

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

但这不起作用。

因为您要查找的是精确匹配而不是模式匹配,所以可以尝试以下方法:

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

df由于您要查找的是精确匹配,而不是模式匹配,因此可以尝试以下方法:

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

df您可以尝试使用sapply

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

[1] 1 0 1 0

你可以试着用sapply

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

[1] 1 0 1 0

我们可以做一个
grep

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

我们可以做一个
grep

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

您也可以进行一些代码压缩
sapply(strsplit(df$site,split=“,”),函数(x)any(x%in%c(3,11))
这些编辑使它完全工作:sapply(strsplit(as.character(df$site),split=“,”),函数(x)any(as.numeric(x)%in%c(11,1)))。谢谢!您也可以进行一些代码压缩
sapply(strsplit(df$site,split=“,”),函数(x)any(x%in%c(3,11))
这些编辑使它完全工作:sapply(strsplit(as.character(df$site),split=“,”),函数(x)any(as.numeric(x)%in%c(11,1)))。谢谢!1和0代表什么?它们是简单的“是”和“否”,还是应该给出每个字符串中的匹配数?这是一个有点悠闲的版本:
library(tidyverse);df%>%group_by(row=row_number())%>%sep='',',',convert=TRUE)%>%SUMMARY(result=as.integer(any(site==11 | site==3))
1和0代表什么?它们是简单的“是”和“否”,还是应该给出每个字符串中的匹配数?这是一个有点悠闲的版本:
library(tidyverse);df%>%group_by(row=row_number())%>%sep='',',',convert=TRUE)%>%SUMMARY(result=as.integer(any(site==11 | site==3))
搜索“1”只会得到1 0 0,这是不正确的。搜索“1”只会得到1 0 0,这是不正确的。