[R] grep

David Winsemius dw|n@em|u@ @end|ng |rom comc@@t@net
Sat May 8 19:05:00 CEST 2021


On 5/8/21 10:00 AM, Steven Yen wrote:
> Below, the first command simply creates a list of 16 names (labels) 
> which can be ignore.
>
> In the 2nd and 3rd commands, I am able to identify names containing 
> "black".
>
> In line 4, I am trying to identify names containing "black" or 
> "conserv" but obviously it does not work. Can someone help? Thanks.
>
> > names<-names(tp.nohs$estimate)[c(1:8,58:65)]; names
>  [1] "x1.one"      "x1.black"    "x1.othrrace" "x1.moddkna" 
> "x1.conserv"  "x1.nstrprty"
>  [7] "x1.strrep"   "x1.sevngprt" "x2.one"      "x2.black" 
> "x2.othrrace" "x2.moddkna"
> [13] "x2.conserv"  "x2.nstrprty" "x2.strrep"   "x2.sevngprt"
> > grep("black",names,value=TRUE)
> [1] "x1.black" "x2.black"
> > grep("black",names,value=FALSE)
> [1]  2 10
> > grep(c("black","conserv"),names,value=TRUE)
> [1] "x1.black" "x2.black"
> Warning message:
> In grep(c("black", "conserv"), names, value = TRUE) :
>   argument 'pattern' has length > 1 and only the first element will be 
> used


Try using the logical OR operator (vertical bar, AKA "pipe")

grep(c("black|conserv"), names, value=TRUE)

-- 

David.

>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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