[R] subsetting levels of a vector

Marc Schwartz marc_schwartz at me.com
Fri Aug 10 16:58:58 CEST 2012


On Aug 10, 2012, at 4:07 AM, simona mancini <mancinisimona at yahoo.it> wrote:

> Hi,
> 
> 
> I need to subset different levels of vector in a dataset to create a new dataframe that contains only these. These observations are not numerical, so I can't use the subset() function (at least this is the response I get from R).
> Suppose the dataframe looks like this:
> 
> 
> 
>   ParticipID    ERP   Electrode
> 1         s1  0.0370       FP1
> 2         s2 35.0654       FP2
> 3         s3 -3.3852        F4
> 4         s4  2.6119        P3
> 5         s5  0.1224        P4
> 6         s6 -5.3153        O1
> 
> 
> I want to create a subset of the dataframe with only the FP1, FP2, F4 levels of Electrode, how do I do? 
> (actually the levels I have to filter are much more than these three, but this is just to give an example).
> 
> I know this is a trivial question, but I am still getting familiar with R...
> 
> Thanks a lot,
> 
> s.


Take a look at ?subset and ?"%in%, which can be used in this fashion:

  NewDF <- subset(DF, Electrode %in% c("FP1", "FP2", "F4"))

If the levels you do not want are few in number, it may be easier to use:

  NewDF <- subset(DF, !Electrode %in% c("Levels", "You", "Don't", "Want"))

Note the use of '!' before Electrode to negate the boolean logic.

Regards,

Marc Schwartz



More information about the R-help mailing list