0

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?

Dan
  • 11,370
  • 4
  • 43
  • 68
  • When I run it in my console the function runs fine. Instead of `load_all` have you tried to install and restart the package or check package? Can you make data.table a dependency? – Mike Sep 26 '19 at 13:34
  • Yep, you're right about the dependency. The solution is to [RTM](https://cran.r-project.org/web/packages/data.table/vignettes/datatable-importing.html) and include `data.table` in the DESCRIPTION and NAMESPACE files. – Dan Sep 26 '19 at 13:37
  • 1
    see also: https://stackoverflow.com/q/10527072/4550695 – Mikko Marttila Sep 26 '19 at 13:38
  • Thanks, @MikkoMarttila – I'll mark it as a dupe. – Dan Sep 26 '19 at 13:49
  • If you think there is room for improvement on the [Importing `data.table` vignette](https://cran.r-project.org/web/packages/data.table/vignettes/datatable-importing.html), please [file an issue](https://github.com/Rdatatable/data.table/issues) :) – MichaelChirico Sep 26 '19 at 14:02
  • 1
    @MichaelChirico No, I think the vignette is quite clear. The problem was purely that I didn't read it! – Dan Sep 26 '19 at 14:09
  • we havent done too well advertising it! – MichaelChirico Sep 26 '19 at 15:05

0 Answers0