-3

I want to count the number of days rain fell in a month for different years at different location.

This is my data:

Location Year Month Day Precipitation
A        2008 1     1   0
A        2008 1     2   8.32
A        2008 1     3   4.89
A        2008 1     4   0

I have up to 18 locations, year is from 2008 - 2018, 12 months in each year and 0 for precipitation means no rain on that day.

R overflow
  • 1,292
  • 2
  • 17
  • 37
  • 2
    The minimal information you provided makes it hard for people to help you. Check this link for help on how to make a reproducible example: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – TTS Mar 10 '20 at 16:07

2 Answers2

2

You can use aggregate:

aggregate(cbind(days=x$Precipitation > 0), as.list(x[c("Location", "Year", "Month")]), sum)
#  Location Year Month days
#1        A 2008     1    2

Data:

x <- structure(list(Location = structure(c(1L, 1L, 1L, 1L), .Label = "A", class = "factor"), 
    Year = c(2008L, 2008L, 2008L, 2008L), Month = c(1L, 1L, 1L, 
    1L), Day = 1:4, Precipitation = c(0, 8.32, 4.89, 0)), class = "data.frame", row.names = c(NA, -4L))
GKi
  • 37,245
  • 2
  • 26
  • 48
0

Based on the available information

df <- df %>%
  filter(Precipitation != 0) %>%
  group_by(Location, Year, Month) %>%
  summarize(DaysOfRain = n())
TTS
  • 1,818
  • 7
  • 16