user702432
user702432

Reputation: 12178

Conditional subsetting in 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?

Upvotes: 3

Views: 1269

Answers (2)

James
James

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

Ari B. Friedman
Ari B. Friedman

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

Related Questions