按随机间隔选择tibble中的行

问题描述 投票:1回答:1

我正在尝试采用一系列日期 - 从第一个日期开始 - 按照正态分布生成的随机数选择后续日期。目前我的代码通过随机数选择行号,但每次都使用相同的数字。在此示例中,它每12天选择一行:

set.seed(123)

library(tidyverse)
library(lubridate)

start_date <- as.Date('2018-03-01')
end_date <- as.Date('2018-07-01')

seq_dates <- seq(ymd(start_date), ymd(end_date), by='1 days')

seq_dates <- seq_dates %>%
  as.tibble()
seq_dates

seq_dates %>% 
  filter(row_number() %% round(rnorm(n=1, mean=14, sd=3), 0) == 1) 

有没有办法用dplyr做到这一点,但每次都以随机的间隔从开始日期中选择一行?所以从2018-03-01开始,下一个日期可能是12天后,然后是14天后,然后是19天后,等等?

r dplyr tidyverse lubridate
1个回答
2
投票
library(dplyr)

set.seed(10) 
n <- rnorm(50, 14, 3)
rows <- cumsum(round(n, 0))
diff(rows) # random ~normal increments used when selecting your rows
#  [1] 13 10 12 15 15 10 13  9 13 17 16 13 17 16 14 11 13 17 15 12  7 12  8 10 13 12 11 14 13  8 14 17
# [33] 15 10 10 15  9 13 12 17 12 12 17 11 14 15 13 12 16

seq_dates %>% 
  slice(rows[rows <= n()])
# # A tibble: 9 x 1
#   value     
#   <date>    
# 1 2018-03-14
# 2 2018-03-27
# 3 2018-04-06
# 4 2018-04-18
# 5 2018-05-03
# 6 2018-05-18
# 7 2018-05-28
# 8 2018-06-10
# 9 2018-06-19
© www.soinside.com 2019 - 2024. All rights reserved.