R 函数,用于按天迭代列中出现的时间戳
我有一个R中的数据集,在a列mm/dd/yyyy hh:mm 24h中按时间戳降序排序。我希望在B列中创建一个从午夜开始的时间戳的运行计数,用于每个独特的日子。我想得出以下结果: 例如:R 函数,用于按天迭代列中出现的时间戳,r,R,我有一个R中的数据集,在a列mm/dd/yyyy hh:mm 24h中按时间戳降序排序。我希望在B列中创建一个从午夜开始的时间戳的运行计数,用于每个独特的日子。我想得出以下结果: 例如: | Column A | Column B | |-----------------|----------| | 9/26/2019 23:29 | 4 | | 9/26/2019 17:29 | 3 | | 9/26/2019 8:29 | 2 | |
| Column A | Column B |
|-----------------|----------|
| 9/26/2019 23:29 | 4 |
| 9/26/2019 17:29 | 3 |
| 9/26/2019 8:29 | 2 |
| 9/26/2019 1:10 | 1 |
| 9/25/2019 15:21 | 4 |
| 9/25/2019 10:19 | 3 |
| 9/25/2019 5:29 | 2 |
| 9/25/2019 0:29 | 1 |
我已经在Excel中解决了这个问题,在a列中为唯一的mm/dd/yyyy值使用了countif函数。我还没有成功地找到R等价物。使用dplyr,我们可以首先将ColumnA转换为POSIXct格式,按日期分组,然后在每个组中分配秩
library(dplyr)
df %>%
mutate(ColumnA = as.POSIXct(ColumnA, format = "%m/%d/%Y %H:%M", tz = "UTC")) %>%
#Can also use lubridate mdy_hm
#mutate(ColumnA = lubridate:: mdy_hm(ColumnA)) %>%
group_by(group = as.Date(ColumnA)) %>%
mutate(new_col = rank(ColumnA)) %>%
ungroup() %>%
select(-group)
# A tibble: 8 x 3
# ColumnA ColumnB new_col
# <dttm> <int> <dbl>
#1 2019-09-26 23:29:00 4 4
#2 2019-09-26 17:29:00 3 3
#3 2019-09-26 08:29:00 2 2
#4 2019-09-26 01:10:00 1 1
#5 2019-09-25 15:21:00 4 4
#6 2019-09-25 10:19:00 3 3
#7 2019-09-25 05:29:00 2 2
#8 2019-09-25 00:29:00 1 1
资料
使用dplyr,我们可以首先将ColumnA转换为POSIXct格式,按日期分组,然后在每个组中分配排名
library(dplyr)
df %>%
mutate(ColumnA = as.POSIXct(ColumnA, format = "%m/%d/%Y %H:%M", tz = "UTC")) %>%
#Can also use lubridate mdy_hm
#mutate(ColumnA = lubridate:: mdy_hm(ColumnA)) %>%
group_by(group = as.Date(ColumnA)) %>%
mutate(new_col = rank(ColumnA)) %>%
ungroup() %>%
select(-group)
# A tibble: 8 x 3
# ColumnA ColumnB new_col
# <dttm> <int> <dbl>
#1 2019-09-26 23:29:00 4 4
#2 2019-09-26 17:29:00 3 3
#3 2019-09-26 08:29:00 2 2
#4 2019-09-26 01:10:00 1 1
#5 2019-09-25 15:21:00 4 4
#6 2019-09-25 10:19:00 3 3
#7 2019-09-25 05:29:00 2 2
#8 2019-09-25 00:29:00 1 1
资料
假设最后注释中以可复制形式显示的输入,在a中创建a列的POSIXct版本,然后使用ave计算日期内的排名。不使用包
A <- as.POSIXct(DF$A, format = "%m/%d/%Y %H:%M", tz = "GMT")
data.frame(A, B = ave(as.numeric(A), as.Date(A), FUN = rank))
请注意,R中的时间序列通常按升序存储,而不是降序存储
笔记
可复制形式的输入:
Lines <- "| A | B |
| 9/26/2019 23:29 | 4 |
| 9/26/2019 17:29 | 3 |
| 9/26/2019 8:29 | 2 |
| 9/26/2019 1:10 | 1 |
| 9/25/2019 15:21 | 4 |
| 9/25/2019 10:19 | 3 |
| 9/25/2019 5:29 | 2 |
| 9/25/2019 0:29 | 1 |"
DF <- read.table(text = Lines, sep = "|", header = TRUE)["A"]
假设最后注释中以可复制形式显示的输入,在a中创建a列的POSIXct版本,然后使用ave计算日期内的排名。不使用包
A <- as.POSIXct(DF$A, format = "%m/%d/%Y %H:%M", tz = "GMT")
data.frame(A, B = ave(as.numeric(A), as.Date(A), FUN = rank))
请注意,R中的时间序列通常按升序存储,而不是降序存储
笔记
可复制形式的输入:
Lines <- "| A | B |
| 9/26/2019 23:29 | 4 |
| 9/26/2019 17:29 | 3 |
| 9/26/2019 8:29 | 2 |
| 9/26/2019 1:10 | 1 |
| 9/25/2019 15:21 | 4 |
| 9/25/2019 10:19 | 3 |
| 9/25/2019 5:29 | 2 |
| 9/25/2019 0:29 | 1 |"
DF <- read.table(text = Lines, sep = "|", header = TRUE)["A"]