我正在尝试对一个分组的数据帧进行子集,以便每个组只有一行。对于每个组,如果行具有特定值,我希望对其进行子集,但如果不存在这样的行,则我将对另一行进行子集。
数据是按年份和季节分组的,我想使用来自第一季组的Month == 2设置行,使用第二季的Month == 4设置行,使用第三季的Month == 8设置行,并使用第四季的Month == 10设置行。
如果没有包含要求的行,则季节组中具有最大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和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发布于 2019-01-11 00:20:36
检查此解决方案:
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()https://stackoverflow.com/questions/54132659
复制相似问题