【问题标题】:How can I subset for a row that has a target value within a group, and if there are none, subset for a different row within the same group?如何为组中具有目标值的行设置子集,如果没有,则为同一组中的不同行设置子集?
【发布时间】:2019-01-10 16:08:10
【问题描述】:

我正在尝试对分组的数据框进行子集化,以便每个组最终得到一行。对于每个组,如果它具有特定值,我想对一行进行子集化,但如果不存在这样的行,那么我将对替代行进行子集化。

数据按年份和季节分组,我想将第 1 季组中的 Month == 2 行子集,第 2 季组中 Month == 4 的行子集,第 3 季组中 Month == 8 的行子集,并与第 4 季中的 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 

我尝试了以下代码,但不知道如何在同一段代码中包含我的替代要求(我认为这需要ifelse 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

【问题讨论】:

  • 代替==,对多个元素使用%in%

标签: r


【解决方案1】:

检查这个解决方案:

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()

【讨论】:

  • 是的,这行得通!很高兴了解到case_when() :)
猜你喜欢
  • 1970-01-01
  • 2019-04-28
  • 1970-01-01
  • 1970-01-01
  • 2015-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-06
相关资源
最近更新 更多