[R] How to exclude certain columns by column names?

Paul Hiemstra p.hiemstra at geo.uu.nl
Tue Nov 3 10:54:13 CET 2009


Linlin Yan wrote:
> Try this:
>   
>> x[, colnames(x) != 'a']
>>     
And more general:

x[, !colnames(x) %in% c('a','b')]

Paul
> [1] 3 4
>
> On Tue, Nov 3, 2009 at 9:31 AM, Peng Yu <pengyu.ut at gmail.com> wrote:
>   
>> I can exclude columns by column number using '-'. But I wondering if
>> there is an easy way to exclude some columns by column names.
>>
>>     
>>> x=cbind(c(1,2),c(3,4))
>>> x
>>>       
>>     [,1] [,2]
>> [1,]    1    3
>> [2,]    2    4
>>     
>>> colnames(x)=c('a','b')
>>> x
>>>       
>>     a b
>> [1,] 1 3
>> [2,] 2 4
>>     
>>> x[,-'a']
>>>       
>> Error in -"a" : invalid argument to unary operator
>>     
>>> x[,-1]
>>>       
>> [1] 3 4
>>
>> ______________________________________________
>> 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.
>>
>>     
>
> ______________________________________________
> 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.
>   


-- 
Drs. Paul Hiemstra
Department of Physical Geography
Faculty of Geosciences
University of Utrecht
Heidelberglaan 2
P.O. Box 80.115
3508 TC Utrecht
Phone:  +3130 274 3113 Mon-Tue
Phone:  +3130 253 5773 Wed-Fri
http://intamap.geo.uu.nl/~paul




More information about the R-help mailing list