Sebastian Zeki
Sebastian Zeki

Reputation: 6874

how to @importFrom data.table within r package function

I have a function in a package I am developing. I don't think the input data is relevant so I haven't posted it. I am trying to only import specific functions from packages into this function as per recommendations and this mostly works fine apart from for data.table.

#' @importFrom data.table 'setDT' 'rowid' '.SD'
 #' @keywords Sankey
 #' @export
    SurveySankey <- function(dfw, y,PatientID) {
      # Create the Sankey diagrams
      Sankey <-
        dcast(data.table::setDT(dfw)[, .SD, PatientID], 
              PatientID ~ rowid(PatientID),
              value.var = y)
    }

If I do as above I get the error:

1. Error: SurveySankey (@test.R#400) -------------------------------------------------------------------------------------------------
object '.SD' not found

but if instead of the @importfrom statement I use

#' @import data.table

it runs fine. I don't want to use the latter as some of the function names clash with other packages. How can I import .SD - perhaps this isn't the importable function?

Upvotes: 2

Views: 1149

Answers (1)

clemens
clemens

Reputation: 6813

.SD is not a function at all.

In the source code of the package you can see, that .SD is only exported to prevent NOTEs:

.SD = .N = .I = .GRP = .BY = .EACHI = NULL
# These are exported to prevent NOTEs from R CMD check, and checkUsage via compiler.
# But also exporting them makes it clear (to users and other packages) that data.table uses these as symbols.
# And NULL makes it clear (to the R's mask check on loading) that they're variables not functions.
# utils::globalVariables(c(".SD",".N")) was tried as well, but exporting seems better.
# So even though .BY doesn't appear in this file, it should still be NULL here and exported because it's
# defined in SDenv and can be used by users.

You can try to import 'special-symbols' from data.table:

#' @importFrom data.table "special-symbols"

ALternatively, you could just add this line .SD = .N = .I = .GRP = .BY = .EACHI = NULL to your package.

Upvotes: 2

Related Questions