简体   繁体   中英

Subsetting two factors in R

I have a huge dataset, and I have a column called season. There are 4 seasons ie 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.

您还可以将dplyr软件包与filter函数一起使用

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

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")

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM