[R] matching a string with multiple conditions using grep
Rui Barradas
ruipbarradas at sapo.pt
Sat Jun 23 12:52:38 CEST 2012
Hello,
Try the following.
wanted <- c("A_cont_12", "AB_cont_22", "cont_21_Aa")
x <- c("A_cont_1", "A_cont_12", "B_treat_8", "AB_cont_22", "cont_21_Aa")
pattern <- c("A", "cont", "2")
ix <- Reduce(`&`, lapply(pattern, grepl, x)) # This does the trick
identical(wanted, x[ix])
See ?Reduce.
Hope this helps,
Rui Barradas
Em 23-06-2012 11:19, Zhipeng Wang escreveu:
> Suppose I have a vector ["A_cont_1", "A_cont_12", "B_treat_8",
> "AB_cont_22", "cont_21_Aa"], I hope I can extract the strings which include
> 3 short strings, say "A", "cont" and "2", that is to say, "A_cont_12",
> "AB_cont_22" and "cont_21_Aa" will be extract, using a relatively short
> code (using grep?).
> Would you please to give some idea? Thank you !
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list