【问题标题】:r compare max year / month from dataframe to current year month [duplicate]r比较数据框的最大年/月与当年月[重复]
【发布时间】:2020-08-04 09:10:01
【问题描述】:

我有一个与下面类似的数据框,想将年/月的最大值与当年的月份进行比较。问题是,对于 max(month),我得到 12(显然),而对于合并的最大年/月,我得到 2020_12。但我需要的是合并年/月的最大值(所以 2020_03)

df <- data.frame(ID = c(1:6),
                 year = c(2019,2019,2019,2020,2020,2020),
                 month = c(10,11,12,1,2,3))

谁有一个简单的解决方案?

【问题讨论】:

  • 你的预期输出是什么?
  • 只是 2020_03 或 2020_3。我只需要将其与系统日期的年月进行比较,并根据比较结果过滤数据。基本上,我想要做的是将那些在系统日期(或任何其他年/月)的年月之前具有年/月值的记录保留在 DF 中

标签: r date max


【解决方案1】:

你可以先创建一个日期对象:

df <- transform(df, date = as.Date(paste(1, month, year, sep = "-"), '%d-%m-%Y'))

计算max日期

max(df$date)
#[1] "2020-03-01"

要获取df 中最大行的索引,您可以使用which.max

ind <- which.max(df$date)
ind
#[1] 6

如果你想以特定格式输出:

paste(df$year[ind], df$month[ind], sep = "_")
#[1] "2020_3"

【讨论】:

    【解决方案2】:

    不确定你是否想要这个输出:

    df %>%
      group_by(year) %>%
      mutate(max = paste0(year, "_", max(month)))
    
    
        # A tibble: 6 x 4
    # Groups:   year [2]
         ID  year month max    
      <int> <dbl> <dbl> <chr>  
    1     1  2019    10 2019_12
    2     2  2019    11 2019_12
    3     3  2019    12 2019_12
    4     4  2020     1 2020_3 
    5     5  2020     2 2020_3 
    6     6  2020     3 2020_3 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多