如果匹配正则表达式
,我想在数据框列中扩展某些字符串输入:
FD_Object<-list(x="a stricture",x="an ulcer",x="inflammation",x="a nodule",x="a polyp")
FD_Location<-list(x="oesophagus at (cm)",x="GOJ",x="fundus",x="stomach body",x="stomach antrum",x="duodenal bulb",x="D1/D2 angle",x="second part of the duodenum",x="third part of the duodenum")
FD_LesionGen<-list(x="Flat",x="friable",x="nodular",x="malignant-looking")
FD1<-replicate(1000,paste("There is",sample(FD_Object,1,replace=F),"in the",sample(FD_Location,1,replace=F),".It is",sample(3:10,1),"mm in length and ",sample(FD_LesionGen,1,replace=F)))
FD1<-data.frame(FD1)
到目前为止我的尝试:
if (str_detect(FD1[,1],"polyp")){
paste("Hi",FD1[1,])
}
但是我收到了错误:
Error in if (str_match(FD1[, 1], "polyp")) { :
argument is not interpretable as logical
In addition: Warning message:
In if (str_match(FD1[, 1], "polyp")) { :
the condition has length > 1 and only the first element will be used
如何使匹配合乎逻辑?
答案 0 :(得分:1)
您可以使用grepl
:
a <- letters[1:3]
bool <- grepl("b", a)
a[bool] <- paste("pre", a[bool])
答案 1 :(得分:1)
另一种选择可能是
library(dplyr)
library(stringr)
FD1 %>%
mutate(FD1 = ifelse(str_detect(FD1, "polyp"), paste("Hi", FD1), as.character(FD1)))
答案 2 :(得分:0)
尝试str_detect()
而不是str_match()
。
答案 3 :(得分:0)
您的问题是,您要给grepl
或str_detect
一个字符串向量进行检查,以便您的输出是逻辑向量。您可以使用apply
将条件函数单独应用于每个元素:
out <- apply(FD1, 1, function(x) {
if (stringr::str_detect(x, "polyp")) {
return(paste("Hi", x))
} else {
return(x)
}
})