如何将整数更改为日期R.

时间:2013-04-26 13:02:26

标签: r integer

嗨,我在R中得到了一个简单的问题,

我们可以将字符转换为日期,例如

v <- c(2008101, 20081202, 20081103)
date <- as.Date(as.character(v), format("%Y%m%d"));date

但是如何将v<- c(200801, 200802)转换为2008-012008-02

2 个答案:

答案 0 :(得分:2)

如此简单的事情:

##Give each entry a date
v = paste0(v, "01")
##Convert as before
date = as.Date(as.character(v), format("%Y%m%d"));

您甚至可以编写一个小功能来自动执行此操作:

to_date = function(v) {
  v = as.character(v)

  missing_day = nchar(v) < 7
  v[missing_day] = paste0(v[missing_day], "01")
  as.Date(v, format("%Y%m%d"))
}

##Last value is missing the date
v = c(2008101, 20081202, 20081103, 200811)
to_date(v)

答案 1 :(得分:0)

这是另一种选择:

foo <- function(x){
  x <- as.Date(as.character(x), format("%Y%m%d"))
  newDates <- lapply(strsplit(as.character(x), "-"), "[", -2)
  sapply(newDates, function(x) paste(x[1],x[2],  sep="-"))
}

> foo(v)
[1] "2008-01" "2008-02" "2008-03"