【问题标题】:Is there an R function that will rank dates/times by other column criteria?是否有一个 R 函数可以按其他列标准对日期/时间进行排名?
【发布时间】:2019-10-15 08:41:01
【问题描述】:

我有兴趣将 dataf 中的日期列更改为与 id 对应的有序数字(最早日期 = 1,第二早 = 2 ... 等等),如 results$order 中所示。如果一个 id 只出现一次,我希望 order 为 1。

date=c("2012-02-18", "2013-03-01", "2013-04-11", "2013-06-06", "2013-09-20", "2013-07-02")
datef=strptime(date, format="%Y-%m-%d")
dataf=data.frame(id=c(20, 20, 20, 21, 21, 22), 
              date=datef, 
              service=c("web", "phone", "person", "phone", "web", "web"))
> dataf
  id       date service
1 20 2012-02-18     web
2 20 2013-03-01   phone
3 20 2013-04-11  person
4 21 2013-06-06   phone
5 21 2013-09-20     web
6 22 2013-07-02     web

我什至很难找到正确的措辞来寻找这个困境的答案。我想胁迫吗?还是索引?把dataf$dates放到results$order下面?

results=data.frame(id=c(20, 20, 20, 21, 21, 22), 
                   order=c(1,2,3,1,2,1), 
                   service=c("web", "phone", "person", "phone", "web", "web"))

> results
  id order service
1 20     1     web
2 20     2   phone
3 20     3  person
4 21     1   phone
5 21     2     web
6 22     1     web

【问题讨论】:

  • 为什么id=20 电话出现在同一个id 的person 条目之前,它排在第三位?
  • @r2evans 哎呀修复了。

标签: r sorting date rank


【解决方案1】:

dplyr:

library(dplyr)
dataf %>% group_by(id) %>% mutate(order = rank(date))
# # A tibble: 6 x 4
# # Groups:   id [3]
#      id date                service order
#   <dbl> <dttm>              <fct>   <dbl>
# 1    20 2012-02-18 00:00:00 web         1
# 2    20 2013-03-01 00:00:00 phone       2
# 3    20 2013-04-11 00:00:00 person      3
# 4    21 2013-06-06 00:00:00 phone       1
# 5    21 2013-09-20 00:00:00 web         2
# 6    22 2013-07-02 00:00:00 web         1

【讨论】:

  • 我猜正确的搜索词会按日期排列?谢谢
  • 约会并不重要。 “按组排序”很好。但实际上,您只需要找到 rank 函数任何“按组”做事的方法并将它们放在一起。
  • (您也可以在其他答案中使用data.table,但使用dataf[, order := rank(date), by id]
【解决方案2】:

data.table:

library(data.table)

setDT(dataf)

setorder(dataf, id, date)
dataf[, order := 1:.N, by = id]
> dataf
   id       date service order
1: 20 2012-02-18     web     1
2: 20 2013-03-01   phone     2
3: 20 2013-04-11  person     3
4: 21 2013-06-06   phone     1
5: 21 2013-09-20     web     2
6: 22 2013-07-02     web     1

【讨论】:

    猜你喜欢
    • 2020-11-03
    • 1970-01-01
    • 2020-01-03
    • 2018-06-02
    • 1970-01-01
    • 2021-12-27
    • 2021-12-09
    • 2019-10-05
    • 1970-01-01
    相关资源
    最近更新 更多