我的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
包。
所以我需要你的帮助。提前致谢,不要犹豫,或发表评论。