Operator "% m%" with mapply

I am trying to use mapply to add months to current dates in columns a and b of my framework. Here is the code to create a sample data frame:

library(lubridate) a <- as.Date(c("2012-01-11","2012-06-30","2012-04-18")) b <- as.Date(c("2013-04-21","2012-03-22","2012-05-01")) df <- data.frame(a,b) 

I can use mapply("+",df, c(30,30)) to add 30 days to both date columns. However, when I try to use the mapply("%m+%",df, months(1:2)) command mapply("%m+%",df, months(1:2)) , I get an error message:

Error in .setupMethodsTables (fdef, initialize = TRUE): there is no slot name "group" for this object of the class "derivedDefaultMethod"

Is it possible to use mapply with the% m +% operator?

+4
source share
1 answer

For my uninformed S4 eyes, this seems to be a problem with the lubridate package and a way to build %m+% .

Looking at the source ,

It seems that the non- .quick_month_add function .quick_month_add will do what you want

  mapply(lubridate:::.quick_month_add,df,months(1:2), SIMPLIFY = FALSE) $a [1] "2012-01-11" "2012-06-30" "2012-04-18" $b [1] "2013-04-21" "2012-03-22" "2012-05-01" 

note that SIMPLIFY must be set to FALSE , otherwise you will get a digital matrix, since the Date class will be deleted when simplified to a matrix.

Or, Map(lubridate:::.quick_month_add,df,months(1:2))

+1
source

All Articles