r - "%m %"操作符与 mapply

标签 r lubridate

我正在尝试使用 mapply 将月份添加到数据框 a 和 b 列中的当前日期。这是创建示例数据框的代码:

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)

我可以用 mapply("+",df, c(30,30))将 30 天添加到两列日期。但是,当我尝试使用命令 mapply("%m+%",df, months(1:2)) 时我收到错误消息:

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



是否可以将 mapply 与 %m+% 运算符一起使用?

最佳答案

在我 S4 无知的眼中,这似乎是 lubridate 包和 %m+% 方式的问题。方法被构造。

看着 the source ,

看来是未导出的函数.quick_month_add会做你想做的

 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"

请注意 SIMPLIFY必须设置为 FALSE否则,您将获得数字矩阵,因为在简化为矩阵时删除了 Date 类。

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

关于r - "%m %"操作符与 mapply,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14819362/

相关文章:

r - 在 levelplot 中指定 NA 栅格值的颜色(R 包 rasterVis)

r - 在预先排序的列上合并 R 中的数据框?

r - 深入 R 包 : Time Zones in lubridate

r - 如何将sqlite日期转换为R中的日期

r - 润滑至每月的最后一天

r - 如果条件包含 lubridate 包中的 `years` 函数,ifelse 命令总是返回 0

r - 使用 'lubridate'计算时间间隔

database - 如何在远程机器上使用 R 中的 ff 包?

使用 ggplot 对facet_wrap 的级别重新排序

r - Sparklyr 连接错误 : Error in spark_connect_gateway(gatewayAddress, gatewayPort, sessionId, : Gateway in localhost:8880 did not respond