If I use source code then everything is working but when I create package/function then it is giving me an error. Am I missing anything?
test package
test <- function() {
library("data.table")
dd <- mtcars
setDT(dd)
dd$cnt <- 1
eval(parse(text=paste0("dd <- unique(dd[,list(cnt, mpg, cyl)])")))
eval(parse(text=paste0("dd1 <- dd[order(mpg, cyl)]")))
print(dd1)
}
create a package using R CMD build on Linux
test |__R |__test.r |__DESCRIPTION |__NAMESPACE
R CMD build test
R CMD INSTALL test_1.0.tar.gz
Content of DESCRIPTION
Package: test Title: test Version: 1.0 Authors@R: person("xyz", "xyz", email = "[email protected]", role = c("aut", "cre")) Description: test Depends: R (>= 3.6.0) License: test Encoding: UTF-8 LazyData: true Imports: data.table
use function in R
library("test")
test()
Get an error as below
Error in [.data.frame
(x, i, j) : object 'cnt' not fo
R code without package and it is working
library("data.table")
dd <- mtcars
setDT(dd)
dd$cnt <- 1
eval(parse(text=paste0("dd <- unique(dd[,list(cnt, mpg, cyl)])")))
eval(parse(text=paste0("dd1 <- dd[order(mpg, cyl)]")))
print(dd1)
package.skeleton()
function and see what it creates -- it takes more to have a package. Full details are in the Writing R Extensions manual. (And mypkgKitten
package helps with some post-processing ofpackage.skeleton()
which leaves some things you must edit which is confusing when you start out. RStudio also has a package generator helper, as do other packages.) – Dirk Eddelbuettelpackage.skeleton()
function should be your new best friends. I just found it a little off-putting that it would never passR CMD check --as-cran
immediately after creation, hencepkgKitten
. But I use the same approach as you: try first with the minimal amount of helpers to reallly understand the minimal structure. – Dirk Eddelbuetteldata.table
sometimes needs extra care. Did youimport()
it inNAMESPACE
? (And of course you should not havelibrary()
calls in R code in package. See what elseR CMD check
and/or thecheck
button in RStudio say). – Dirk Eddelbuettel