Question

I need to subset a df with two very difficult conditions to code (for me) in R:

Given the following dataframe:

A=as.factor(rep(1:50,3))
B=as.factor(rep(c(1,2,3),50))
C=(rep(rnorm(10,30,3),15)) 
df=data.frame(A,B,C)  

I need to subset rows of that dataframe which, for a given level of a factor A, contains observations of two of the levels from B (ex, the level "1" and the level "2").

Any hint? Thanks in advance Agus

Was it helpful?

Solution

Assuming you want first level of factor A and first 2 levels of factor B

df[df$A %in% levels(df$A)[1] & df$B %in% levels(df$B)[1:2], ]

To change the subset, replace levels(df$A)[1] and levels(df$B)[1:2] by exact values you need.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top