0
$\begingroup$

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?

$\endgroup$
0
$\begingroup$

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.

| improve this answer | |
$\endgroup$
1
$\begingroup$

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)
| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.