Reputation: 12178
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?
Upvotes: 3
Views: 1269
Reputation: 66834
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.
Upvotes: 5
Reputation: 72731
Assuming DF is your data frame and x is the variable within a data.frame:
sel <- ( x > 10 )
a <- DF[ sel, ]
b <- DF[ !sel, ]
Upvotes: 1