代码之家  ›  专栏  ›  技术社区  ›  Antonios

不包括相同日期的数据框排名值

  •  2
  • Antonios  · 技术社区  · 7 年前

    我有一个带有日期和值的数据框:

    library(dplyr)
    library(lubridate) 
    
    df<-tibble(DateTime=ymd(c("2018-01-01","2018-01-01","2018-01-02","2018-01-02","2018-01-03","2018-01-03")),
                  Value=c(5,10,12,3,9,11),Rank=rep(0,6))
    

    我想对最后两行的值进行排序,每一行与其余四行(以前日期的值)进行比较。

    我已设法做到这一点:

    dfReference<-df%>%filter(DateTime!=max(DateTime))
    
    dfTarget<-df%>%filter(DateTime==max(DateTime))
    
    for (i in 1:nrow(dfTarget)){
      tempDf<-rbind(dfReference,dfTarget[i,])%>%
        mutate(Rank=rank(Value,ties.method = "first"))
      dfTarget$Rank[i]=filter(tempDf,DateTime==max(df$DateTime))$Rank
    }
    

    期望输出:

    > dfTarget
    # A tibble: 2 x 3
      DateTime   Value  Rank
      <date>     <dbl> <dbl>
    1 2018-01-03     9     3
    2 2018-01-03    11     4
    

    但我正在寻找一种更微妙的方式。

    谢谢

    1 回复  |  直到 7 年前
        1
  •  3
  •   IceCreamToucan    7 年前

    这与你的想法基本相同 for 循环,但不是它使用的循环 map_int ,而不是使用 rbind 它创建了一个新的向量 c() .

    library(tidyverse)
    
    is.max <- with(df,  DateTime == max(DateTime))
    
    df[is.max,] %>% 
      mutate(Rank = map_int(Value, ~
        c(df$Value[!is.max], .x) %>% 
          rank(ties.method = 'first') %>% 
          tail(1)))
    
    
    
    # # A tibble: 2 x 3
    #   DateTime   Value  Rank
    #   <date>     <dbl> <int>
    # 1 2018-01-03     9     3
    # 2 2018-01-03    11     4