在包中构建时,Data.table聚合函数不起作用

时间:2017-04-28 20:26:30

标签: r data.table devtools

我的data.table包的聚合函数遇到了一个非常奇怪的问题。当我在一个脚本文件中逐行运行它时,它完美无缺。当我把它放在该脚本文件中的函数时。

但是,当我想构建自己的R包并使用@export标记相同的函数以使其可调用时,则代码会中断。当我在没有标签的情况下将该函数隐藏在包中的另一个可调用函数中时,它也会中断。

我可以给你一个小例子数据集。但是记得测试它,你必须启动一个新的R package项目并标记和构建函数。

这是:它只是在变量上建立一个总和。

# Example input data set df1
require(lubridate)
days = 365*2
date = seq(as.Date("2000-01-01"), length = days, by = "day")
year = year(date)
month = month(date)
x1 = cumsum(rnorm(days, 0.05)) 
df1 = data.frame(date, year, month, x1)

# Manual approach - called line by line. Works as expected
library(data.table)
df2 <- setDT(df1)[, lapply(.SD, mean), by=.(year, month), .SDcols = "x1"]
setDF(df2)
df2

# The aggregation function in the script file. 
testAggregationInScript <- function(df) {
  library(data.table)
  df2 <- setDT(df)[, lapply(.SD, mean), by=.(year, month), .SDcols = "x1"]
  setDF(df2)
  return(df2)
}

# Call the function of the script file. Works as expected
df3.script <- testAggregationInScript(df1)


# -----------------
# In the test R package build the test aggregation function

#' If the function is in a package and built and then called, it breaks
#' 
#' @export
testAggregationInPackage <- function(df) {
  library(data.table)
  df2 <- setDT(df)[, lapply(.SD, mean), by=.(year, month), .SDcols = "x1"]
  setDF(df2)
  return(df2)
}

# -----------------

# -----------------
# Back in the R script

# Call the function from the R package in an R script
# Here the code fails due to some strange error. Although everything seems the same
library(testRpackage)
df3.package <- testAggregationInPackage(df1)

控制台中的错误消息非常模糊:

Error in .subset(x, j) : invalid subscript type 'list'
Called from: `[.data.frame`(x, i, j)

我真的不明白。似乎输入不一样。传递参数时,R可能会更改输入格式或包函数的内容。或者它只是我身边的蠢事^^

我测试了其他聚合函数,例如来自dplyr包,它们通常与data.table包一起工作。但我无法转换到另一种方法,我必须使用data.table包。

所以我需要你的帮助。提前致谢,不要犹豫,或发表评论。

1 个答案:

答案 0 :(得分:1)

devtools包似乎仍然存在问题。你可以阅读here。什么给了我一个很好的提示是this早期的stackoverflow问题。

总之,方法如下:

  1. 在函数所在的R包的脚本文件中添加#' @import data.table
  2. import(data.table)语句添加到NAMESPACE文件
  3. 虽然我已经有Imports: data.table,但我还在Depends: data.table文件中添加了DESCRIPTION
  4. 然后我重建了它并重新安装它