Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional subsetting in R

Tags:

r

I have a dataframe "df". I want to create two subsets (a & b) from a conditional statement, say, variable "x" having value greater than 10. In SAS, this would be something like: data a, b; set df; if x>10 then output a; else output b. Is there a way to do this in R?

like image 979
user702432 Avatar asked Jul 08 '26 04:07

user702432


2 Answers

You could use split:

subs <- split(df,df$x>10)
a <- subs[[1]]
b <- subs[[2]]

The second argument of split takes a factor, so you can use more complex statements to give more splits.

like image 189
James Avatar answered Jul 12 '26 09:07

James


Assuming DF is your data frame and x is the variable within a data.frame:

sel <- ( x > 10 )
a <- DF[ sel, ]
b <- DF[ !sel, ]
like image 31
Ari B. Friedman Avatar answered Jul 12 '26 11:07

Ari B. Friedman



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!