# How to keep a subsetted value for calculating mean

I am currently learning R and I have to solve an Issue were I have to extract values from a data set which are from a specific month and from this values I should calculate the mean Temp.

I did it like that:

data[data$X..Month.. == 6,] mean(data$X..Temp.., na.rm=TRUE)

It gave me the mean value but without taking my first statement into consideration. What do I need to do that both statements are taken into consideration?

To just get the mean for month 6:

mean(df$temp[df$mon=="Jun"], na.rm=T)


You were nearly there but didn't assign your subset to a value, if you had:

x = data[data$X..Month.. == 6,] mean(x$X..Temp.., na.rm=TRUE)


that should work.

You can answer this using tapply, which will give you the mean for all your subsets, e.g.

dummy data

df = data.frame(mon=rep(month.abb, times=10)


calculate mean for all months

tapply(df$temp, df$mon, mean, na.rm=T)