data.table不同时接受“ by”和“ format”(日期)

ros*_*ova 5 r data.table

我一直data.table在寻找“会话”的平均日期,但是在尝试以所需的方式格式化它时遇到了麻烦,并且我对问题所在感到困惑:

library( data.table )
data <- data.table( session = c( 1,1,1,1,2,2,2,2,2,2,3,3,3,3 ),
                    date = as.Date( c( "2016-01-01", "2016-01-02", "2016-01-03", "2016-01-03",
                                       "2016-04-30", "2016-04-30", "2016-05-03", "2016-05-03", "2016-05-03", "2016-05-03",
                                       "2016-08-28", "2016-08-28", "2016-08-28", "2016-08-28" ) )
)
Run Code Online (Sandbox Code Playgroud)

我要给每个会话一个标签,基于该会话的时间。我已决定将每个会话标记为该会话发生的月份(格式为“%b-%Y”),但是由于这些会话有时会跨越2个月,因此我想通过获取该会话的平均日期来完成此操作会话,并以此来确定标签。

我可以使用by参数找到每个会话的平均日期:

output <- copy( data )[ , Month := mean( date ), by = session ]
Run Code Online (Sandbox Code Playgroud)

我还可以按照自己想要的方式重新格式化平均日期data.table

output <- copy( data )[ , Month := format( mean( date ), "%b-%Y" ) ]
Run Code Online (Sandbox Code Playgroud)

但是我不能两者都做:

output <- copy( data )[ , Month := format( mean( date ), "%b-%Y" ), by = session ]
Run Code Online (Sandbox Code Playgroud)

上面的返回错误:

Error in prettyNum(.Internal(format(x, trim, digits, nsmall, width, 3L,  : 
invalid 'trim' argument
In addition: Warning message:
In mean(date) : argument is not numeric or logical: returning NA
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么?该代码对我来说似乎正确,并且每个部分都工作正常,那么为什么这不起作用?

请注意,我可以按照以下两个步骤来完成我需要做的事情,并且工作正常,但是我很想知道我丢失了什么。上面的代码有问题,我只是看不到它是什么:

output <- copy( data )[ , Month := mean( date ), by = session 
                        ][ , Month := format( Month, "%b-%Y" ) ]
Run Code Online (Sandbox Code Playgroud)

Hub*_*rtL 3

如果您使用mean.Date而不是:它会起作用mean

output <- copy( data )[ , Month := format( mean.Date( date ), format="%b-%Y" ), by = session ]
Run Code Online (Sandbox Code Playgroud)

这样它就利用了format.Date