[R] Selecting subset of factor levels

David Winsemius dwinsemius at comcast.net
Thu Aug 18 16:39:29 CEST 2011


On Aug 18, 2011, at 10:27 AM, B Jessop wrote:

>
>
> Dear r-help,
>
> I would like to select a subset of levels from a factor variable in  
> a data frame and return a data frame.
>
> The data set consists of 3 variables, 2 of which are factors (Site,  
> Fish) and one numeric (Datavalue) as follows:
>
> Site  Fish   Datavalue
>
> AB     2-1    2.3
> AB     2-1    2.4
> AB     2-1    2.2
> AB     2-2    2.6
> AB     2-2    2.5
> AB     2-2    2.7
> AB     2-3    1.6
> AB     2-3    1.5
> AB     2-3    1.4
> etc
> AB     2-20   3.1
> AB     2-20   2.9
> AB     2-20   3.0
>
> I would like to create a subset containing all variable rows but for  
> only, say, Fish 2-1, 2-2, and 2-3.  The following code:
>

subset(Df1, Fish %in% c("2-1", "2-2", "2-3")

factors are not ordered (by default anyway) so the ":" (seq) operator  
has no meaning;



> Df2 <- subset(Df1, Eel=="2-1" | Eel=="2-3") selects only Eel 2-1 and  
> 2-3.  The use of a ":" rather than "|" gives an error message.  My  
> other approaches did not work.  Any

Eel? What????
>
> suggestions for doing this task would be much appreciated.
>
>
>
> Regards,
>
> BJ
>  		 	   		
> ______________________________________________
> 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list