【问题标题】:Convert Month and Year and Day to SAS formatted date将月、年和日转换为 SAS 格式的日期
【发布时间】:2018-09-13 22:07:44
【问题描述】:

Ciao,我需要帮助将月列、年列和日期列转换为 SAS 格式的日期。 SAS 日期值是表示 1960 年 1 月 1 日与指定日期之间的天数的值。 SAS 可以对从公元 1582 年到公元 19,900 年的日期进行计算。 1960 年 1 月 1 日之前的日期是负数; 1960 年 1 月 1 日之后的日期是正数。例如:month=9,year=1992,day = 1, date=11946

【问题讨论】:

  • 我们在 1992 年 9 月的示例日期中缺少一天。

标签: r date sas lubridate


【解决方案1】:

您可以使用difftime

ss <- "1992-9-15"
difftime(as.Date(ss), as.Date("1960-01-01"))
#Time difference of 11946 days

您没有为示例日期指定一天,但向后推算得出 1992 年 9 月 15 日。

存储为numeric

date_for_SAS <- as.numeric(difftime(as.Date(ss), as.Date("1960-01-01")))
date_for_SAS
#[1] 11946

更新

如果您有一个data.frame,其中包含三列daymonthyear,您可以执行以下操作

df <- data.frame(
    day = c(1:10),
    month = rep(9, 10),
    year = rep(1992, 10))

df$date_for_SAS <- as.numeric(difftime(
    as.Date(sprintf("%s-%s-%s", df$year, df$month, df$day)),
    as.Date("1960-01-01")))
#   day month year date_for_SAS
#1    1     9 1992        11932
#2    2     9 1992        11933
#3    3     9 1992        11934
#4    4     9 1992        11935
#5    5     9 1992        11936
#6    6     9 1992        11937
#7    7     9 1992        11938
#8    8     9 1992        11939
#9    9     9 1992        11940
#10  10     9 1992        11941

【讨论】:

  • 谢谢。现在假设我在数据框 DATA 中有一个 YEAR 列和 MONTH 列。我可以完成这项工作吗: date_for_SAS
猜你喜欢
  • 2015-04-29
  • 1970-01-01
  • 1970-01-01
  • 2021-04-12
  • 1970-01-01
  • 2021-12-12
相关资源
最近更新 更多