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!
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: