[R] Extracting columns with specific string in their names

Dennis Murphy djmuser at gmail.com
Mon Aug 22 19:45:28 CEST 2011


Hi:

You need a leading ^ in your grep string. Here's a reproducible
example to illustrate:

df <- data.frame(Xyz1 = rnorm(5), Xyz2 = rnorm(5), Xyz3 = rnorm(5),
                  Abc1 = rnorm(5), Abc2 = rnorm(5))
df[, grep('^Xyz', names(df))]
df[, grep('^Abc', names(df))]

HTH,
Dennis

On Mon, Aug 22, 2011 at 7:33 AM, Jay <josip.2000 at gmail.com> wrote:
> Hi,
>
> Let's say that I have a set of column names that begin with the string
> "Xyz". How do I extract these specific columns? I tried to do the
> following:
>
> dataframe1[,grep("Xyz",colnames(dataframe1))]
>
> But it does not work. What is wrong with my expression?
>
> ______________________________________________
> 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