[R] R Subset by Factor levels

Rasmus Liland jr@| @end|ng |rom po@teo@no
Wed Jul 29 16:38:01 CEST 2020


Dear Engin,

On 2020-07-29 16:57 +0300, Engin Yılmaz wrote:
> Dear
> 
> I try to create a new subset from my dataframe.
> My dataframe's name is m1.
> "Classification Description" column has 15 different factors.
> The following code is used creating a subset for 1 factor.
> m2<-m1[m1$`Classification Description` == levels(m1$`Classification
> Description`)[1],]
> 
> My aim is to create a subset with 4 different factors. For example,
> levels(m1$`Classification Description`)[1]
> levels(m1$`Classification Description`)[15]
> levels(m1$`Classification Description`)[2]
> levels(m1$`Classification Description`)[4]
> 
> I try to following code but it didnt work
> 
> m2<-m1[m1$`Classification Description` == levels(m1$`Classification
> Description`)[c(1,15,2,4],]

You're almost correct, you just need to 
use match instead of ==:

	m1[m1$`Classification Description` %in%
	   levels(m1$`Classification Description`)[c(1, 15, 2, 4)],]

Read more about it at ?match (?`%in%`).

Best,
Rasmus

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20200729/dc629e17/attachment.sig>


More information about the R-help mailing list