[R] Regular Expressions in grep

R. Michael Weylandt michael.weylandt at gmail.com
Tue Aug 21 21:38:37 CEST 2012


You're misreading the docs: from grep,

   value: if ‘FALSE’, a vector containing the (‘integer’) indices of
          the matches determined by ‘grep’ is returned, and if ‘TRUE’,
          a vector containing the matching elements themselves is
          returned.

Since there's a match somewhere in a[1], all of a[1] is returned (it
is a matching element), not just the matching bit: grep(x, value =
TRUE) is something like x[grepl(x)] to my mind.

I think you want ?regexpr or possibly just substitute out the
non-match with gsub.

Cheers,
Michael

On Tue, Aug 21, 2012 at 2:24 PM, Dr. Holger van Lishaut
<H.v.Lishaut at gmx.de> wrote:
> Dear r-help members,
>
> I have a number in the form of a string, say:
>
> a<-"-01020.909200"
>
> I'd like to extract "1020." as well as ".9092"
>
> Front<-grep(pattern="[1-9]+[0-9]*\\.", value=TRUE, x=a, fixed=FALSE)
> End<-grep(pattern="\\.[0-9]*[1-9]+", value=TRUE, x=a, fixed=FALSE)
>
> However, both strings give "-01020.909200", exactly a.
> Could you please point me to what is wrong?
>
> Thanks and best regards
> H. van Lishaut
>
> ______________________________________________
> 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