返回数据框中R中最小日期和最大日期之间的样本日期

时间:2017-04-03 08:51:51

标签: r stat

如何在数据框中将R中的最小日期和最大日期之间的样本日期作为附加列返回?

Course MinEnrollmentDate MaxEnrollmentDate
Maths 3/11/2016 3/4/2016
Chemistry 6/11/2016 6/4/2016
Physics 9/11/2016 9/4/2016
English 12/11/2016 12/4/2016
Science 3/11/2017 3/4/2017

4 个答案:

答案 0 :(得分:1)

我们可以使用dplyr

library(dplyr)

df <- df %>% 
    rowwise() %>% 
    mutate(MinEnrollmentDate = as.Date(MinEnrollmentDate, format = '%m/%d/%Y'),
           MaxEnrollmentDate = as.Date(MaxEnrollmentDate, format = '%m/%d/%Y'), 
           sampleDate = sample(seq(MinEnrollmentDate, MaxEnrollmentDate, '-1 day'), 1))

df
#> Source: local data frame [5 x 4]
#> Groups: <by row>
#> 
#> # A tibble: 5 x 4
#>      Course MinEnrollmentDate MaxEnrollmentDate  sampleDate
#>       <chr>            <date>            <date>      <date>
#> 1     Maths        2016-03-11        2016-03-04  2016-03-08
#> 2 Chemistry        2016-06-11        2016-06-04  2016-06-09
#> 3   Physics        2016-09-11        2016-09-04  2016-09-06
#> 4   English        2016-12-11        2016-12-04  2016-12-09
#> 5   Science        2017-03-11        2017-03-04  2017-03-06

我不确定我的日期格式是否正确,不明确,请随时更正format=部分。 数据:

df <-  read.table(text = 'Course MinEnrollmentDate MaxEnrollmentDate
                  Maths 3/11/2016 3/4/2016
                  Chemistry 6/11/2016 6/4/2016
                  Physics 9/11/2016 9/4/2016
                  English 12/11/2016 12/4/2016
                  Science 3/11/2017 3/4/2017', header = T, stringsAsFactors = F)

答案 1 :(得分:1)

您可以计算两个日期之间的天数:

days <- as.Date(data$MinEnrollmentDate, format="%d/%m/%Y") - as.Date(data$MaxEnrollmentDate, format="%d/%m/%Y")

然后将MinEnrollmentDate之间的随机数添加到MaxEnrollmentDate的{​​{1}}之间的随机数:

sample()

答案 2 :(得分:0)

假设您正在处理名为mydata的数据框,您可以使用以下代码段:

mydata$sampledate <- sample(seq(as.Date(mydata$MinEnrollmentDate), as.Date(mydata$MinEnrollmentDate), by="day"), 1)

基本上,这样做首先会在开始日期和结束日期之间生成一整天的序列,然后从该序列中获取大小为1的随机样本,并将其写入数据帧。

答案 3 :(得分:0)

为了完整起见,逐步lubridate解决方案(使用GGamba的df):

if (!require(lubridate)) {
  install.packages("lubridate")
}

df <-  read.table(text = 'Course MinEnrollmentDate MaxEnrollmentDate
                  Maths 3/11/2016 3/4/2016
                  Chemistry 6/11/2016 6/4/2016
                  Physics 9/11/2016 9/4/2016
                  English 12/11/2016 12/4/2016
                  Science 3/11/2017 3/4/2017', header = T, stringsAsFactors = F)

no_days <- as.POSIXct(df$MinEnrollmentDate, format = "%d/%m/%Y") - as.POSIXct(df$MaxEnrollmentDate, format = "%d/%m/%Y")

random_days <- sapply(no_days, function(x) sample(x = 1:x, size = 1, replace = T) )

df$random_date <- as.POSIXct(df$MinEnrollmentDate, format = "%d/%m/%Y") + days(random_days)