r - 按随机间隔选择 tibble 中的行
问题描述
我正在尝试获取一系列日期 - 从第一个日期开始 - 通过从正态分布生成的随机数选择后续日期。目前我有通过随机数选择行号的代码,但每次都使用相同的数字。在此示例中,它每 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 天后,等等?
解决方案
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
推荐阅读
- c# - UWP 构建在 VSTS/TFS 构建代理(自托管管道)上失败
- sql - 提交后 SQL 事务意外回滚
- tensorflow - Kaggle TPU 不可用:无法连接到所有地址
- javascript - add a tag inside template literals
- c++ - Minimum Cost to reduce the size of array to 1
- python - 为 firebase-admin sdk 缓存 firestore 数据的最佳方法是什么?
- reactjs - npm WARN deprecated tar@2.2.2: 此版本的 tar 不再受支持,并且不会收到安全更新。请尽快升级
- javascript - 如何在 connect-src(csp) 中使用 nonce 或 sha?
- azure-devops - 如何在 Azure DevOps UI 中创建仅限时间的字段
- php - 如何初始化从easypay数组返回的每个值?