-1

I am new to R and this forum. I try to extract several rows out of a column and work with them, e.g. calculate the mean of it. I was looking for similar questions but did not find exactly what i wanted. Any help will be highly appreciated. I hope the following lines will show my problem clearly. First, here is an reproducible example:

library(data.table)
counts<-matrix(c(0.3343,0.3543,0.3846,0.3713,0.8341,
0.5764,0.3543,0.8341,0.3846,1,2,3,4,5,6,1,2,3,7,7,7,8,8,8,9,9,9), ncol=3)
colnames(counts) <- c('value','doy','month')
counts2 <- data.table(counts)
counts2[month == 7, list(M1 = mean(value))]

This code gives me the mean of month 7. What i want is the mean of the values from month 7 AND 8.

Thanks a lot in advance!

Baldrian
  • 21
  • 4

1 Answers1

0

In that case we use %in% to find the aggregated mean

counts2[month %in% c(7,8), list(M1 = mean(value))]

Or if we need it separately, use the by option

counts2[month %in% c(7,8), list(M1 = mean(value)), by = month]
#   month        M1
#1:     7 0.3577333
#2:     8 0.5939333
akrun
  • 874,273
  • 37
  • 540
  • 662