如何获得按两个不同因素分组的多列的平均值?

时间:2019-02-08 09:55:53

标签: r dplyr

我想获取按站分组的系列列的均值,但按年份将其分开。

我的数据看起来像这样

+---------+------+-------+------+------+------+
| station | year | month | tmax | tmin | rain |
+---------+------+-------+------+------+------+
| A       | 2006 |     1 |   15 |   15 | NA   |
| A       | 2006 |     2 |   25 |   16 | 4    |
| A       | 2006 |     3 |   30 |   18 | 7    |
| A       | 2006 |     4 |   40 |   18 | 5    |
| A       | 2007 |     1 |   15 |   15 | 6    |
| A       | 2007 |     2 |   25 |   16 | 8    |
| A       | 2007 |     3 |   30 |   18 | 10   |
| A       | 2007 |     4 |   40 |   18 | 3    |
| A       | 2008 |     1 |   15 |   15 | 5    |
| A       | 2008 |     2 |   25 |   16 | 8    |
| A       | 2008 |     3 |   30 |   18 | 1    |
| A       | 2008 |     4 |   40 |   18 | 3    |
| B       | 2006 |     1 |   15 |   15 | NA   |
| B       | 2006 |     2 |   25 |   16 | 4    |
| B       | 2006 |     3 |   30 |   18 | 7    |
| B       | 2006 |     4 |   40 |   18 | 5    |
| B       | 2007 |     1 |   15 |   15 | 6    |
| B       | 2007 |     2 |   25 |   16 |      |
| B       | 2007 |     3 |   30 |   18 |      |
| B       | 2007 |     4 |   40 |   18 |      |
| B       | 2008 |       |      |      |      |
+---------+------+-------+------+------+------+

我已经尝试过了,但是我觉得我完全没有把握要点,并且没有得到想要的输出

t <- NewData %>% group_by(station) %>%
  summarise_at(vars(-station, -year), funs(mean(., na.rm=TRUE)))

我想获得类似这样的输出

+---------+------+------+------+------+
| station | year | tmax | tmin | rain |
+---------+------+------+------+------+
| A       | 2006 |   15 |   15 | NA   |
| A       | 2007 |   25 |   16 | 4    |
| A       | 2008 |   30 |   18 | 7    |
| B       | 2006 |   40 |   18 | 5    |
| B       | 2007 |   15 |   15 | 6    |
| B       | 2008 |   25 |   16 | 8    |
| C       | 2006 |   30 |   18 | 10   |
| C       | 2007 |   40 |   18 | 3    |
| C       | 2008 |   15 |   15 | 5    |
+---------+------+------+------+------+

谢谢!

0 个答案:

没有答案