[R] excluding a column from a data frame

Chuck Cleland ccleland at optonline.net
Wed Apr 15 10:36:59 CEST 2009


On 4/15/2009 1:38 AM, Erin Hodgess wrote:
> Dear R People:
> 
> Suppose I have the following data frame:
> 
>           x1         x2       x3
> 1 -0.1582116 0.06635783 1.765448
> 2 -1.1407422 0.47235664 0.615931
> 3  0.8702362 2.32301341 2.653805
>> str(xx)
> 'data.frame':   3 obs. of  3 variables:
>  $ x1: num  -0.158 -1.141 0.87
>  $ x2: num  0.0664 0.4724 2.323
>  $ x3: num  1.765 0.616 2.654
> 
> I can exclude the second column nicely via:
>> xx[,-2]
>           x1       x3
> 1 -0.1582116 1.765448
> 2 -1.1407422 0.615931
> 3  0.8702362 2.653805
> 
> Now suppose I wanted to exclude the column called "x2".  If I try:
>> xx[,-"x2"]
> Error in -"x2" : invalid argument to unary operator
> 
> things don't work.  Is there a simple way to do this by name rather
> than number, please?

  Another way to do it is with subset():

subset(xx, select = -x2)

> Thanks,
> Erin 

-- 
Chuck Cleland, Ph.D.
NDRI, Inc. (www.ndri.org)
71 West 23rd Street, 8th floor
New York, NY 10010
tel: (212) 845-4495 (Tu, Th)
tel: (732) 512-0171 (M, W, F)
fax: (917) 438-0894




More information about the R-help mailing list