Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using apply to convert dates in R and handling NA dates

This seems like it should be a lot easier and I'm sure someone can help me. I'm trying to change each date to the first of its respective month from a data.frame of dates using floor_date() in the lubridate package, however some of those dates are NAs. I'd rather not substitute dummy dates for the NAs.

I've tried the below:

library(lubridate)
a<-c(as.Date("2011-05-04"), as.Date("2011-06-12"))
b<-c(as.Date("2012-03-01"), NA)
test <- data.frame(a,b)

apply(test, 1, function(y) sapply(y, function(x) if(!is.na(x)) floor_date(x, "month") else na.pass(x)))
apply(test, 1, function(y) ifelse(!is.na(y)), floor_date(y, "month"), na.pass(y))

The first call returns:

Error in object[[name, exact = TRUE]] : subscript out of bounds

The second call returns:

Error in update.default(x, mdays = 1, hours = 0, minutes = 0, seconds = 0) : 
need an object with call component

Thank you for any help!

like image 404
tcash21 Avatar asked Sep 19 '25 23:09

tcash21


2 Answers

I don't know about lubridate, but you could do this easily with the excellent date-handling facilities provided by base R.

Here's a little helper function that should perform the calculations you want without complaint:

firstOfMonth <- function(dates) {
    as.Date(strftime(dates, format="%Y-%m-01"))
}

firstOfMonth(a)
# [1] "2011-05-01" "2011-06-01"
firstOfMonth(b)
# [1] "2012-03-01" NA   

data.frame(lapply(test, firstOfMonth))
#            a          b
# 1 2011-05-01 2012-03-01
# 2 2011-06-01       <NA>
like image 199
Josh O'Brien Avatar answered Sep 22 '25 12:09

Josh O'Brien


Have you tried package zoo ?

library(zoo)
a<-c(as.Date("2011-05-04"), as.Date("2011-06-12"))
b<-c(as.Date("2012-03-01"), NA)
test <- data.frame(
        "a" = as.Date(as.yearmon(a)),
        "b" = as.Date(as.yearmon(b))
)
like image 22
b_rousseau Avatar answered Sep 22 '25 12:09

b_rousseau