根据数据帧中的条件使用带sample()的循环

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

我有一个数据集,其中包含从此代码生成的日期:

library(chron)
dates <- seq.dates("1/1/2019", "1/6/2020", by = "days")
week <- c(1:53)
day <- c("tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", 
"monday")
weeks <- rep(1:53, each = 7)
dates_df <- data.frame(date=dates, day=day, week=weeks)

而且我正在尝试使用带有sample()的循环从每周随机选择3天而无需替换但我似乎无法找到一种方法在我的循环中指示我需要为dates_df中的每个整数采样3次$ week然后转到下周。

我不能简单地对一组序列进行采样(例如7天),因为在实际日历中,某些月份在一周中间结束。

有没有办法根据数据框中的其他值有条件地使用sample()?

r random conditional sample
1个回答
1
投票

我们可以使用sample_n包中的group_bydplyr

library(dplyr)

dates_df %>%
    group_by(week) %>%
    sample_n(3)

#    date        day        week
#    <S3: dates> <fct>     <int>
#  1 01/03/19    thursday      1
#  2 01/07/19    monday        1
#  3 01/04/19    friday        1
#  4 01/10/19    thursday      2
#  5 01/08/19    tuesday       2
#  6 01/13/19    sunday        2
#  7 01/16/19    wednesday     3
#  8 01/17/19    thursday      3
#  9 01/21/19    monday        3
#  ....

对于每周,sample_n函数将选择三个日期。 sample_n的默认值是无需替换的样本。

这是使用R的基本by解决方案:

do.call('rbind', # bind by row
        by(dates_df, dates_df$week, # split data by week
           FUN = function(d) d[sample(nrow(d), 3),])) # sample

#            date       day week
# 1.5    01/05/19  saturday    1
# 1.3    01/03/19  thursday    1
# 1.7    01/07/19    monday    1
# 2.13   01/13/19    sunday    2
# 2.9    01/09/19 wednesday    2
# 2.8    01/08/19   tuesday    2
# ...
© www.soinside.com 2019 - 2024. All rights reserved.