Skip to content
Back to formatted view

Raw Message

Message-ID: <2e7f26fa-cfc1-d3c8-7575-c03c4a32402d@sapo.pt>
Date: 2021-05-08T19:02:32Z
From: Rui Barradas
Subject: grep
In-Reply-To: <95812983-6A72-4392-A293-43CF974E3FF7@dcn.davis.ca.us>

Hello,

The pattern can be assembled with paste(., collapse = "|").
With the same vector of names, nms:


words <- c("black","conserv")
pattern <- paste(words, collapse = "|")
grep(pattern = pattern, nms, value = TRUE)
#[1] "x1.black"   "x1.conserv" "x2.black"   "x2.conserv"


Hope this helps,

Rui Barradas

?s 18:20 de 08/05/21, Jeff Newmiller escreveu:
> Regular expression patterns are not vectorized... only the data to be searched are. Use one of the many websites dedicated to tutoring regular expressions to learn how they work. (Using function names like "names" as data names is bad practice.)
> 
> nms <- c( "x1.one", "x1.black", "x1.othrrace", "x1.moddkna", "x1.conserv", "x1.nstrprty", "x1.strrep", "x1.sevngprt", "x2.one", "x2.black", "x2.othrrace", "x2.moddkna", "x2.conserv", "x2.nstrprty", "x2.strrep", "x2.sevngprt" )
> 
> grep( "black|conserv", nms, value = TRUE )
> 
> On May 8, 2021 10:00:12 AM PDT, Steven Yen <styen at ntu.edu.tw> 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
>>
>> ______________________________________________
>> R-help at 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.
>