【发布时间】:2020-06-17 12:25:49
【问题描述】:
我有一个看起来像这样的数据框
dt GNDVI YEAR week
<date> <dbl> <chr> <dbl>
1 2002-07-04 0.646 2002 27
2 2002-07-07 0.627 2002 27
3 2002-07-08 0.514 2002 27
4 2002-07-09 0.614 2002 28
5 2002-07-11 0.654 2002 28
6 2002-07-14 0.64 2002 28
7 2002-07-18 0.673 2002 29
8 2002-07-20 0.653 2002 29
我已经按周对数据进行了分组。现在我想过滤 2002-2019 年每周的变量 GNDVI 的最大值。 我当前的代码返回 2002-2019 年 GNDVI 最高的总周数,而不是分别返回每一年。
library(dplyr)
library(lubridate)
library(tidyverse)
options(stringsAsFactors = FALSE)
library(data.table)
#setting dt as dateclass column
gndvi_daily$dt<-as.Date(gndvi_daily$dt)
#selecting months of choice
GS=gndvi_daily[month(gndvi_daily$dt) >= 6 & month(gndvi_daily$dt) <=
9, ]
#extract year from dateclass column
GS$YEAR <- substr(GS$dt, 1,4)
#group GNDVI by week
GSWEEK = GS %>% group_by(week = week(dt))
#iterating to filter maximum GNDVI per week of all years 2002-2019
output <- vector ("double", 0)
for(i in seq_along(GSWEEK$YEAR)) {output <- tapply(GSWEEK$GNDVI,
GSWEEK$week, max)}
output
当前输出:
22 0.651
23 0.711
24 0.699
....
40 0.648
需要的输出:
week year Max GNDVI
22 2002 0.651
23 2002 0.711
...
39 2019 0.88
40 2019 0.67
我对 R 中的编码有点陌生,我非常感谢任何帮助。
【问题讨论】: