[R] deleting rows containing a letter
David Winsemius
dwinsemius at comcast.net
Wed May 11 16:06:14 CEST 2011
On May 11, 2011, at 10:01 AM, David Winsemius wrote:
>
> On May 11, 2011, at 7:55 AM, chris20 wrote:
>
>> Hi
>> I have dataframe with different plot numbers in and different
>> subplots as
>> letters at the end of the plot number i.e. 1a, 1b 2-1a etc.
>> I want to delete all rows that end in a specific letter eg...
>>
>> treat<-c("1a","1b","1c","2a","2b","2c","2-1a","2-1b","2-1c")
>> a1<-1:9
>> b1<-9:1
>> d1<-data.frame(treat,a1,b1)
>>
> > d1[-grep("c$", d1$treat), ]
> treat a1 b1
> 1 1a 1 9
> 2 1b 2 8
> 4 2a 4 6
> 5 2b 5 5
> 7 2-1a 7 3
> 8 2-1b 8 2
>
>> How do I remove all rows where treat ends in "c" ? I have tried
>> the usual
>> ways of deleting rows but nothing works.
>
> Not sure what the usual ways are for you but negative indexing is
> the usual way for me.
>
> (Could also use subset, I suppose)
As here with grepl rather than grep:
> subset(d1, !grepl("c$", d1$treat))
treat a1 b1
1 1a 1 9
2 1b 2 8
4 2a 4 6
5 2b 5 5
7 2-1a 7 3
8 2-1b 8 2
In case you are new to grepping, the $ indicates the end of a string
and therefore 'c' will match any 'c' at the end of the string. grepl
creates a logical vector that flags matches and non-matches and the
'!' operator logically inverts it.
David Winsemius, MD
West Hartford, CT
More information about the R-help
mailing list