“%m%" mapply运算符 [英] "%m %" operator with mapply

查看:100
本文介绍了“%m%" mapply运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

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

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:

.setupMethodsTables(fdef,initialize = TRUE)中的错误:没有插槽 类"derivedDefaultMethod"的该对象的名称"group"

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

是否可以通过%m +%运算符使用mapply?

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

推荐答案

在我对S4不了解的人看来,这与lubridate软件包和%m+%方法的构造方式有关.

To my S4 ignorant eyes, this appears to be an issue with the lubridate package and the way the %m+% method is constructed.

查看

未导出的函数.quick_month_add似乎可以满足您的要求

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"

请注意,必须将SIMPLIFY设置为FALSE,否则当简化为矩阵时,由于Date类被剥离,因此您将获得数字矩阵.

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.

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

这篇关于“%m%" mapply运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆