在R中将向量转换为日期

时间:2013-11-29 03:21:27

标签: 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确切知道每个双周对应的日期?谢谢你的帮助!

2 个答案:

答案 0 :(得分:0)

您可以缩短此代码。我已经分开了每一步以帮助理解,但你可以用一长串代码完成它。

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
[1] "BW01.68" "BW02.68" "BW26.10" "BW22.13"
> dates
[1] "1968-01-15" "1968-01-29" "2010-12-31" "2013-11-05"
> mondaydates
[1] "1968-01-15" "1968-01-29" "2010-12-27" "2013-11-04"

PS:请注意,您要确定数据中bw的测量方式以及是否正确翻译。您应该能够操作它以使其工作,例如您可能会遇到bw 27。

答案 1 :(得分:0)

另一种解决方案。

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"

虽然我会注意到“双周”似乎是一个奇怪的措施,但我不能确定只使用14天的积木是你工作的目的。