Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

specifying conditions as a variable to subset a data frame in R

Tags:

r

Suppose I have a data frame, df with 30 columns: A1 to A30. I know that I can subset this data frame by writing a command like:

 filteredrows = subset(df, A1 == 30 & A2 == 2 & A3 == "this")

The above example filters data based on values in three columns, but I have to do this for values in about say 12 columns. Writing those 12 values in the subset() function will make it too long. To make the code cleaner, is there a way I can specify the condition as a variable or a function and then use that specify the conditions in the subset function. Is something like the following possible?

x = (A1 == 30 & A2 == 2 & A3 == "this")
filteredrows = subset(df, x)

Thanks in advance.

like image 642
Curious2learn Avatar asked Oct 28 '25 04:10

Curious2learn


1 Answers

You can specify the condition as an expression and then pass it to subset using eval:

d <- data.frame(x=letters[1:10],y=runif(10))
ss <- expression(x == "a")
subset(d, eval(ss))
like image 140
joran Avatar answered Oct 29 '25 19:10

joran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!