R 不包括相同日期的数据框排名值
我有一个带有日期和值的数据框:R 不包括相同日期的数据框排名值,r,dplyr,R,Dplyr,我有一个带有日期和值的数据框: 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)) 库(dplyr) 图书馆(lubridate) df目标 #一个ti
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))
库(dplyr)
图书馆(lubridate)
df目标
#一个tibble:2x3
日期时间值秩
1 2018-01-03 9 3
2 2018-01-03 11 4
但我正在寻找一种更微妙的方式
感谢这基本上与
for
循环的想法相同,但它使用map\u int
,而不是使用rbind
创建新的数据帧,而是使用c()创建新的向量
库(tidyverse)
是最大值%
变异(秩=map_int(值~
c(df$值[!is.max],.x)%>%
排名(ties.method='first')%>%
尾(1)))
##tibble:2 x 3
#日期时间值秩
#
# 1 2018-01-03 9 3
# 2 2018-01-03 11 4
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
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