Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make vapply return a date vector?

Tags:

date

loops

r

How can I make vapply return a date vector? (I think that's a different problem: Returning a vector of class POSIXct with vapply ):

f1 <- function(x) {
  as.Date(paste0("2000", sprintf("%02d", x), "01"), format = "%Y%m%d")
}

vapply(3:7, f1, as.Date("2000-01-01"))
# [1] 11017 11048 11078 11109 11139

Want:

# "2000-03-01" "2000-04-01"  "2000-05-01"  "2000-06-01"  "2000-07-01"
like image 478
r.user.05apr Avatar asked Dec 06 '25 20:12

r.user.05apr


1 Answers

The problem is that apply family functions drop Date class. Here is one way to do it:

do.call("c", lapply(3:7, f1))

You can also add class(result) <- "Date" after evaluating vapply.

Full version of class(result) <- "Date":

result <- vapply(3:7, f1, numeric(1))
class(result) <- "Date"
result
# "2000-03-01" "2000-04-01" "2000-05-01" "2000-06-01" "2000-07-01"
like image 191
Clemsang Avatar answered Dec 09 '25 11:12

Clemsang