You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用R在指定时间区间内每月生成一个随机日期?

Hey there! I see the issue with your current code—when you sample directly from all days in the date range, there's no guarantee you'll get one date per month. Let's fix that by targeting each month individually, so we're guaranteed exactly one random date per month.

Solution 1: Using Base R (no extra packages needed)

First, we'll define the start and end dates for each month in your range, then pick one random day from each month:

# Generate the first day of each month in your target range
month_starts <- seq(as.Date("2020-01-01"), as.Date("2020-09-01"), by = "month")

# Calculate the last day of each month (next month's first day minus 1 day)
month_ends <- c(seq(as.Date("2020-02-01"), as.Date("2020-10-01"), by = "month") - 1)

# For each month, sample one random day
random_dates <- sapply(1:length(month_starts), function(i) {
  sample(seq(month_starts[i], month_ends[i], by = "day"), 1)
})

# Convert to a data frame
df <- data.frame(Date = as.Date(random_dates, origin = "1970-01-01"))

Solution 2: Using lubridate (for cleaner code)

If you're okay with using the lubridate package (great for simplifying date handling), this code is more concise:

library(lubridate)

# Create a sequence of the first day of each target month
target_months <- seq(ymd("2020-01-01"), ymd("2020-09-01"), by = "month")

# Sample one random day per month
random_dates <- purrr::map(target_months, function(month) {
  # Get the last day of the current month
  month_end <- ceiling_date(month, "month") - days(1)
  # Sample one day from the month's date range
  sample(seq(month, month_end, by = "day"), 1)
}) %>% 
  unlist() %>% 
  as.Date()

# Make the final data frame
df <- data.frame(Date = random_dates)

Verify the Result

To confirm you have exactly one date per month, run this quick check:

table(format(df$Date, "%Y-%m"))

You'll see each month from 2020-01 to 2020-09 listed with a count of 1, confirming no duplicates across months.

内容的提问来源于stack exchange,提问作者Varun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 10:52:52