将向量转换为R中的日期

将向量转换为R中的日期,r,date,vector,R,Date,Vector,我有一个日期向量,形式为BW01.68,BW02.68,BW26.10。BW代表“双周”,例如,“BW01.68”代表1968年的第一个双周,“BW26.10”代表2010年的第26个(也是最后一个)双周。使用R,我如何将这个向量转换成实际日期,比如说,01-01-1968,01-15-1968,12-16-2010? 有没有办法让R知道每两周对应的确切日期?谢谢你的帮助 您可以将此代码缩短很多。我已经将每一步隔开以帮助理解,但您可以在一行(长)代码中完成它 bw <- c('BW01.6

我有一个日期向量,形式为BW01.68,BW02.68,BW26.10。BW代表“双周”,例如,“BW01.68”代表1968年的第一个双周,“BW26.10”代表2010年的第26个(也是最后一个)双周。使用R,我如何将这个向量转换成实际日期,比如说,01-01-1968,01-15-1968,12-16-2010? 有没有办法让R知道每两周对应的确切日期?谢谢你的帮助

您可以将此代码缩短很多。我已经将每一步隔开以帮助理解,但您可以在一行(长)代码中完成它

bw <- c('BW01.68', 'BW02.68','BW26.10','BW22.13')

# the gsub will ensure that bw01.1 the same as bw01.01, bw1.01, or bw1.1

#isolating year no
yearno <- as.numeric(
  gsub(
    x = bw,
    pattern = "BW.*\\.",
    replacement = ""
    )
)

#isolating and converting bw to no of days
dayno <- 14 * as.numeric(
  gsub(
    x = bw,
    pattern = "BW|\\.[[:digit:]]{1,2}",
    replacement = ""
  )
)

#cutoff year chosen as 15
yearno <- yearno + 1900
yearno[yearno < 1915] <- yearno[yearno < 1915] + 100


# identifying dates
dates <- as.Date(paste0('01/01/',yearno),"%d/%m/%Y") + dayno
# specifically identifinyg mondays of that week no
mondaydates <- dates - as.numeric(strftime(dates,'%w')) + 1

附言:只是要注意,你是如何在你的数据中测量bw的,以及你是否正确地翻译它。您应该能够操作它以使其正常工作,例如,您可能会遇到BW27。

另一种解决方案

biwks <- c("BW01.68", "BW02.68", "BW26.10")

bw <- substr(biwks,3,4)
yr <- substr(biwks,6,7)
yr <- paste0(ifelse(as.numeric(yr) > 15,"19","20"),yr)

# the %j in the date format is the number of days into the year
as.Date(paste(((as.numeric(bw)-1) * 14) + 1,yr,sep="-"),format="%j-%Y")

#[1] "1968-01-01" "1968-01-15" "2010-12-17"

biwks你的约会尊重一周中的哪一天?所有返回的值应该是星期一(或其他某一天),还是可以是这两周内的任何日期?我认为这与一周中的哪一天无关。
biwks <- c("BW01.68", "BW02.68", "BW26.10")

bw <- substr(biwks,3,4)
yr <- substr(biwks,6,7)
yr <- paste0(ifelse(as.numeric(yr) > 15,"19","20"),yr)

# the %j in the date format is the number of days into the year
as.Date(paste(((as.numeric(bw)-1) * 14) + 1,yr,sep="-"),format="%j-%Y")

#[1] "1968-01-01" "1968-01-15" "2010-12-17"