[R] deleting column from data frame

David Winsemius dwinsemius at comcast.net
Tue Feb 23 17:39:21 CET 2010


On Feb 23, 2010, at 10:13 AM, adam naples wrote:

> try
>
> test <- subset(test, select = -c(Y))

That approach has the deficiency (or feature?) that it will throw an  
error if Y is not a column in test, whereas test[ , -grep("Y",  
names(test))] will not.

However, the grep approach will return an empty dataframe when given a  
non-existent column name which seems very unintuitive. I think the  
best approach is:

 > test[,!names(test)%in%"A"] # same as
 > test[,!colnames(test)%in%"A"]
   X Y  Z
1 1 5  8
2 2 6  9
3 3 7 10
4 4 8 11

-- 
David.
>
> The key is the  minus sign before c() in the select argument.
> You can put in as many columns as you like.
> -a
>
> On Feb 23, 2010, at 11:02 AM, David Winsemius wrote:
>
>>
>> On Feb 23, 2010, at 6:04 AM, Knut Krueger wrote:
>>
>>> Hi to all,
>>> test <- data.frame("X"=c(1:4),"Y"=c(5:8),"Z"=c(8:11))
>>> test <- test[,-2]
>>>
>>> Is there a way to specify the col name  "Y" to delete instead the  
>>> number?
>>>
>>
>> I believe that negative indexing only works with numeric arguments.  
>> You could dummy up a negation approach for character vectors with:
>>
>> > test[, !(names(test) %in% c("Y"))]   #non-negated logical vector  
>> to index
>>  X  Z
>> 1 1  8
>> 2 2  9
>> 3 3 10
>> 4 4 11
>>
>> > test[, -grep("Y",names(test))]  # negated numeric vector to index
>>  X  Z
>> 1 1  8
>> 2 2  9
>> 3 3 10
>> 4 4 11
>>
>> -- 
>> David
>>> Kind regards Knut
>>>
>>> ______________________________________________
>>> 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.
>
> The information contained in this message may be privileged and  
> confidential. If you are NOT the intended recipient, please notify  
> the sender immediately with a copy to hipaa.security at yale.edu and  
> destroy this message.
>
> Please be aware that email communication can be intercepted in  
> transmission or misdirected. Your use of email to communicate  
> protected health information to us indicates that you acknowledge  
> and accept the possible risks associated with such communication.  
> Please consider communicating any sensitive information by  
> telephone, fax or mail. If you do not wish to have your information  
> sent by email, please contact the sender immediately.
>
>
>



More information about the R-help mailing list