[R] Using grep() to subset lines of text

Gabor Grothendieck ggrothendieck at gmail.com
Sat Nov 29 13:12:54 CET 2008


Try this:

> a <- 2:3
> b <- c("aaa 2 aaa", "2 aaa", "3 aaa", "aaa 3 aaa")
>
> re <- paste("^(", paste(a, collapse = "|"), ")", sep = "")
> re
[1] "^(2|3)"
> grep(re, b, value = TRUE)
[1] "2 aaa" "3 aaa"

On Sat, Nov 29, 2008 at 7:00 AM, ppaarrkk <simon_ecc at yahoo.co.uk> wrote:
>
> I have two vectors, a and b. b is a text file. I want to find in b those
> elements of a which occur at the beginning of the line in b. I have the
> following code, but it only returns a value for the first value in a, but I
> want both. Any ideas please.
>
>
> a = c(2,3)
>
> b = NULL
> b[1] = "aaa 2 aaa"
> b[2] = "2 aaa"
> b[3] = "3 aaa"
> b[4] = "aaa 3 aaa"
>
> grep(paste("^",a, sep=""), b )
>
> --
> View this message in context: http://www.nabble.com/Using-grep%28%29-to-subset-lines-of-text-tp20746365p20746365.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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