R 按随机间隔选择TIBLE中的行

R 按随机间隔选择TIBLE中的行,r,dplyr,tidyverse,lubridate,R,Dplyr,Tidyverse,Lubridate,我试着取一系列日期——从第一个日期开始——用正态分布生成的随机数选择后续日期。目前,我有一个代码,它通过一个随机数选择行号,但每次都使用相同的数字。在本例中,它每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

我试着取一系列日期——从第一个日期开始——用正态分布生成的随机数选择后续日期。目前,我有一个代码,它通过一个随机数选择行号,但每次都使用相同的数字。在本例中,它每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) 
set.seed(123)
图书馆(tidyverse)
图书馆(lubridate)
开始日期
库(dplyr)
种子(10)
N
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