0

我在数据框中有 2 个日期变量 WK_BEGIN_DT 和 WK_END_DT,比如 DAT。这两个都是字符格式。我正在尝试获得以下内容。我在这里使用 SAS 命令,但想在 R 中做同样的事情。

我的数据如下所示:

var1    Begin_DT      End_DT
 1    02/07/2012    02/11/2012
 2    04/09/2012    04/15/2012
 3    04/17/2012    04/23/2012
 4    06/21/2012    06/30/2012
 5    07/15/2012    07/29/2012

SAS代码:

DATA DAT;
  set DAT;
## PART 1: ##

  WK_BEGIN_DT = BEGIN_DT - 2 ;
  WK_END_DT   = WK_BEGIN_DT + 6 ;

## PART 2: ##

  if WEEKDAY(WK_END_DT) ^= 6 then do ;
    if weekday(WK_END_DT) = 7 then WK_END_DT = WK_END_DT + 6 ;
      else WK_END_DT = WK_END_DT + 6 - weekday(WK_END_DT) ; 
  end ;

对于第 1 部分问题,我尝试了

DAT$new.dt <- DAT$wk_end_dt - as.difftime(2, unit="days")

计算后,结果应如下所示:

var1    Begin_DT      End_DT      Wk_Begin_DT  WK_END_DT
 1    02/07/2012    02/11/2012    02/05/2012  02/12/2012
 2    04/09/2012    04/15/2012    04/07/2012  04/15/2012
 3    04/17/2012    04/23/2012    04/15/2012  04/23/2012
 4    06/21/2012    06/30/2012    06/19/2012  06/25/2012
 5    07/15/2012    07/29/2012    07/13/2012  07/21/2012

但它显示以下错误:

Error in `$<-.data.frame`(`*tmp*`, "new.dt", value = numeric(0)) : 
  replacement has 0 rows, data has 2354

谁能帮助我如何获得第 1 部分和第 2 部分的结果?

谢谢你。问候,

4

1 回答 1

2
df <- read.table(textConnection("var1    Begin_DT      End_DT
 1    02/07/2012    02/11/2012
 2    04/09/2012    04/15/2012
 3    04/17/2012    04/23/2012
 4    06/21/2012    06/30/2012
 5    07/15/2012    07/29/2012"), header = T)

# Then typecast your dates to a date format
df$Begin_DT <- as.Date(strptime(df$Begin_DT, "%m/%d/%Y"))
df$End_DT <- as.Date(strptime(df$End_DT, "%m/%d/%Y"))

df$Week_begin <- df$Begin_DT - 2
df$Week_end <- df$Week_begin + 6

library(plyr)
library(lubridate)
# If you dont have these packages, 
# run install.packages('plyr') and install.packages('lubridate')
ddply(df, .(Week_end), function(x) {
     if(day(x$Week_end) !=6 && day(x$Week_end) == 7) {
                x$Week_end <- x$Week_end + 6
            } else {
                x$Week_end <- x$Week_end + 6 - wday(x$Week_end)
            }
     x
    })
于 2012-10-03T17:37:34.690 回答