问题
I am trying to use mapply to add months to the current dates in columns a and b of my dataframe. 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 columns of dates. However, when I try to use the command mapply("%m+%",df, months(1:2))
I get the error message:
Error in .setupMethodsTables(fdef, initialize = TRUE) : no slot of name "group" for this object of class "derivedDefaultMethod"
Is it possible to use mapply with the %m+% operator?
回答1:
To my S4 ignorant eyes, this appears to be an issue with the lubridate package and the way the %m+%
method is constructed.
Looking at the source,
It appears that the unexported 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 numeric matrix as the Date class is stripped when simplifying to a matrix.
Or, Map(lubridate:::.quick_month_add,df,months(1:2))
来源:https://stackoverflow.com/questions/14819362/m-operator-with-mapply