Re: [R] Selecting data frame components by name - do you know a shorter way?

From: roger bos <roger.bos_at_gmail.com>
Date: Sat 21 Jan 2006 - 05:26:44 EST

One idea is to keep the variable names you want in a vector, say 'use' and and get the indices using the match function:

match(use, names(df)

where use <- c("item1","item2",...)

You can then subset the data frame as follows:

newdf <- df[, match(use, names(df)]

HTH, Roger

On 1/20/06, Chuck Cleland <ccleland@optonline.net> wrote:
>
> ?subset
>
> subset(dframe, select=c("name1", "name2", "name3"))
>
> Michael Reinecke wrote:
> > Hi! I suspect there must be an easy way to access components of a data
> frame by name, i.e. the input should look like "name1 name2 name3 ..." and
> the output be a data frame of those components with the corresponding names.
> I īve been trying for hours, but only found the long way to do it (which is
> not feasible, since I have lots of components to select):
> >
> >
> >
> > dframe[names(dframe)=="name1" | dframe=="name2" | dframe=="name3"]
> >
> >
> >
> > Do you know a shortcut?
> >
> >
> >
> > Michael
> >
> >
> > [[alternative HTML version deleted]]
> >
> >
> >
> > ------------------------------------------------------------------------
> >
> > ______________________________________________
> > R-help@stat.math.ethz.ch mailing list
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html
>
> --
> Chuck Cleland, Ph.D.
> NDRI, Inc.
> 71 West 23rd Street, 8th floor
> New York, NY 10010
> tel: (212) 845-4495 (Tu, Th)
> tel: (732) 452-1424 (M, W, F)
> fax: (917) 438-0894
>
> ______________________________________________
> R-help@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html
>

        [[alternative HTML version deleted]]



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Sat Jan 21 05:34:23 2006

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:42:08 EST