我试图对一个分组的数据框进行子集处理,以便最后为每个组添加一行。对于每个组,我想对具有特定值的行进行子集化,但是如果不存在这样的行,那么我将对另一行进行子集化。
数据按年份和季节分组,我想将Month == 2
第1季度组的行,Month == 4
第2季度的行,Month == 8
第3季度的行和Month == 10
第4季度的行作为子集。
如果没有要求的行,则季节组中最大的value
行将是子集。例如,在第4行和第5行中,第4行将是子集。
Year Season Month value
2012 1 1 3.4
2012 1 2 6.1
2012 1 3 9.0
2012 2 5 4.4
2012 2 6 1.2
2012 3 8 4.9
2012 4 10 2.7
2013 1 3 8.3
2013 1 3 2.4
2013 2 4 7.0
2013 3 7 12.1
2013 3 8 5.7
2013 4 10 6.3
2013 4 11 3.3
所需的输出是:
Year Season Month value
2012 1 2 6.1
2012 2 5 4.4
2012 3 8 4.9
2012 4 10 2.7
2013 1 3 8.3
2013 2 4 7.0
2013 3 8 5.7
2013 4 10 6.3
我已经尝试了以下代码,但无法弄清楚如何在同一段代码中包含我的替代要求(我认为这需要使用if
and else if
?)
df %>%
group_by(Year, Season) %>%
slice(which(Month == 2 | Month == 4 | Month == 8 | Month == 10))
#slice(which.max(value)) #selects row with largest value in each group
检查此解决方案:
data %>%
mutate(cond = case_when(
Season == 1 & Month == 2 ~ 1,
Season == 2 & Month == 4 ~ 1,
Season == 3 & Month == 8 ~ 1,
Season == 4 & Month == 10 ~ 1,
TRUE ~ 0
)) %>%
group_by(Year, Season) %>%
arrange(desc(cond), desc(Value)) %>%
slice(1) %>%
ungroup()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句