Joanna
Joanna

Reputation: 673

R: select subsets from a dataframe using multiple conditions

I would like to ask a data manipulation question by R.

This is the original data frame:

group<-c(rep("a",3), rep("b",4), rep("c",3))
interval<-c(c("1st", "2nd", "3rd"),c("1st", "2nd", "3rd","4th"),c("1st", "2nd", "3rd"))
age<-c(c(10, 20, 23),c(12, 22, 24,30),c(17, 24, 25))

data1<-data.frame(group, interval, age)

enter image description here

I would like to set a R code to get the subsets of matrix: first subset, if the age is less than 15 and another subset, if age is more than 20. later on, I have to apply some functions on each subset (my original matrix is long and many conditions have to apply).

So how can I get the subsets of a matrix using different conditions for each subset using loop:

[![enter image description here][2]][2]

I want to use subset() function in loop:

Can anyone help me out?

Thank you!

I appreciate any replies!

Upvotes: 1

Views: 108

Answers (1)

HubertL
HubertL

Reputation: 19544

Without using subset, you can do:

data1[ group %in% data1[data1$interval=="1st" & data1$age<15, "group"] & 
       data1$interval=="2nd",]

Upvotes: 2

Related Questions