I have created a package in R. The default hello.R file created by RStudio contains only the code below.
# Test function
foo <- function(x, y){
# Create data table
dt <- data.table::data.table(x = x, y = y)
#Check
print(data.table::is.data.table(dt))
print(dt)
print(dt[, .(x)])
}
I then run devtools::load_all() to load the package and try running this function as follows:
foo(1:10, 1:10)
# [1] TRUE
# x y
# 1: 1 1
# 2: 2 2
# 3: 3 3
# 4: 4 4
# 5: 5 5
# 6: 6 6
# 7: 7 7
# 8: 8 8
# 9: 9 9
# 10: 10 10
# Error in .(x) : could not find function "."
So, TRUE indicates that it creates a data.table, the data.table is printed and looks good, but it fails when I try to use . to see just one column (i.e., x).
Okay, perhaps my package doesn't know about . because data.table isn't loaded, so I'll use list() instead which is equivalent to .() according to the documentation.
# Test function
foo <- function(x, y){
# Create data table
dt <- data.table::data.table(x = x, y = y)
#Check
print(data.table::is.data.table(dt))
print(dt)
print(dt[, list(x)])
}
and I run devtools::load_all() then call the function as before.
foo(1:10, 1:10)
# [1] TRUE
# x y
# 1: 1 1
# 2: 2 2
# 3: 3 3
# 4: 4 4
# 5: 5 5
# 6: 6 6
# 7: 7 7
# 8: 8 8
# 9: 9 9
# 10: 10 10
# Error in .subset(x, j) : invalid subscript type 'list'
Hmmm. Weird, as list is a base function so clearly the package knows about it. Why can I not select a column using the usual data.table syntax from within my R package?