[R] Quick GREP challenge

Sarah Goslee sarah.goslee at gmail.com
Thu Aug 26 13:47:13 CEST 2010


It isn't entirely clear what you are trying to do - your grep() statement
simply returns the entire string you started with.

But to turn that string into a vector, you will need some combination
of gsub(), strsplit(), and as.numeric() with the exact values depending
on the exact form of the output returned by grep. By c(1, 22) do you
mean a vector (my first assumption), or do you actually mean the
string "c(1, 22)"?

If the former, maybe something like this:

> x <- "f1=5,f22=3"
> x <- gsub("=[0-9]+", "", x)
> x
[1] "f1,f22"
> x <- gsub("f", "", x)
> x
[1] "1,22"
> x <- strsplit(x, ",")
> x
[[1]]
[1] "1"  "22"

> x <- unlist(x)
> x
[1] "1"  "22"
> x <- as.numeric(x)
> x
[1]  1 22

Sarah

On Thu, Aug 26, 2010 at 6:16 AM, Dimitri Shvorob
<dimitri.shvorob at gmail.com> wrote:
>
>> grep("f[0-9]+=", "f1=5,f22=3,", value = T)
> [1] "f1=5,f22=3,"
>
> How do I make the line output c("f1", "f22") instead? (Actually, c(1,22)
> would be even better).
>
> Thank you.
>
>


-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list