Srivats Chari
Srivats Chari

Reputation: 85

Subsetting two factors in R

I have a huge dataset, and I have a column called season. There are 4 seasons i.e. Winter, Spring, Summer and Autumn.

Region  Year    Male    Female  Area    DATE    Day Month   Season
WEST    1996    0   1   4   06-04-96    Saturday    April   Spring
EAST    1996    0   1   16  29-06-96    Saturday    June    Summer
WEST    1996    0   1   4   19-10-96    Saturday    October Winter
WEST    1996    0   1   4   20-10-96    Sunday  October Winter
EAST    1996    0   1   16  01-11-96    Friday  November    Winter
EAST    1996    0   1   16  11-11-96    Monday  November    Winter
WEST    1996    0   1   4   19-11-96    Tuesday November    Winter
WEST    1996    0   1   4   28-11-96    Thursday    November    Winter
WEST    1996    0   1   4   10-12-96    Tuesday December    Winter
WEST    1997    0   1   4   17-01-97    Friday  January Winter
WEST    1997    0   1   4   28-03-97    Friday  March   Spring

So I am trying to create a subset where I want R to show me entries with season as Winter and Autumn.

I created a subset first of the portion I want.

secondphase<-subset(eb1, Area>16)

now from this subset, I want where Season is Winter and Autumn.

I tried these codes-

th2<-subset(secondphase, Season== "Winter")
th3<-subset(secondphase, Season=="Autumn")

Now is there a way to merge these two subsets? or create a subset where I can select the conditions where I want area>16, season should be Winter and autumn.

Thanks for the Help.

Upvotes: 0

Views: 106

Answers (3)

submartingale
submartingale

Reputation: 755

With a data.table approach,

library("data.table")
DT<-data.table(eb1)
subsetDT<-subset(DT, Season %in% c("Autmn","Winter") & Area > 16)

does the job.

Upvotes: 0

johnsinclair
johnsinclair

Reputation: 109

You could also use the dplyr package with the filter function

filter(secondphase, grepl("Winter|Autumn", Season))

Upvotes: 1

Hack-R
Hack-R

Reputation: 23214

Method 1

my_subset <- eb1[eb1$Season %in% c("Winter", "Autumn") & eb1$Area > 16,]

Method 2

th2   <- subset(secondphase, Season== "Winter")
th3   <- subset(secondphase, Season=="Autumn")
final <- rbind(th2, th3)

Method 3

final <-subset(eb1[eb1$Area > 16,], Season== "Winter" | Season=="Autumn")

Upvotes: 0

Related Questions