Wis786
Wis786

Reputation: 53

Subsetting Data based on selected months in R

Year         tot_precip
1/1/1989     0
1/2/1989    .23
1/3/1989    0
1/4/1989    .43
1/5/1989    0.254
1/6/1989    0
1/7/1989    0
1/8/1989    0
1/9/1989    0
1/10/1989   .21

I am trying to subset my precipitation data based on certain months.I did some research.

tt=as.POSIXct(paste(prec$Year,prec$tot_precip), format="%m/%d/%Y")
datZoo <- zoo(prec[,-c(1,2)], tt)
month <- function (x) as.numeric(format(x, "%m"))
veranoIdx <- which(month(tt) %in% 6:8)
veranoZoo <- datZoo[veranoIdx]
veranoZoo

The above code worked to extract Year column based on certain months (June,July august) but I am lost about how to extract precipitation values for those dates(i.e veranoZoo series)

Upvotes: 0

Views: 2016

Answers (2)

Aramis7d
Aramis7d

Reputation: 2496

Considering input as:

dft <- read.table(header = TRUE, text = "Year         tot_precip

                  1/1/1989     0

                  1/2/1989    .23

                  1/3/1989    0

                  1/4/1989    .43

                  1/5/1989    0.254

                  1/6/1989    0

                  1/7/1989    0

                  1/8/1989    0

                  1/9/1989    0

                  1/10/1989   .21",stringsAsFactors=FALSE)

you can just use tidyverse functions and try:

dft %>% filter(month(Year) %in% c(6,7,8))

which gives:

      Year tot_precip
1 1/6/1989          0
2 1/7/1989          0
3 1/8/1989          0

Upvotes: 0

G. Grothendieck
G. Grothendieck

Reputation: 270248

Assuming Lines as in the Note below, read the data into a zoo object. Since this is evidently monthly data it would be best to use "yearmon" class as the index. Now use subset to get the subset for June, July, August.

z <- read.zoo(text = Lines, header = TRUE, FUN = as.yearmon, format = "%d/%m/%Y")
subset(z, cycle(z) %in% 6:8)

giving this zoo series:

Jun 1989 Jul 1989 Aug 1989 
       0        0        0 

This would also work:

z[cycle(z) %in% 6:8]

(If your data is in a file myfile.dat then replace text=Lines with just "myfile.dat" in the read.zoo statement.)

Note:

Lines <- "Year tot_precip
1/1/1989 0
1/2/1989 .23
1/3/1989 0
1/4/1989 .43
1/5/1989 0.254
1/6/1989 0
1/7/1989 0
1/8/1989 0
1/9/1989 0
1/10/1989 .21"

Upvotes: 2

Related Questions