1
votes

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)
1
Look into the 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 my pkgKitten package helps with some post-processing of package.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 Eddelbuettel
Thanks, I added more details into the directory structure of packages. I will look into package.skeleton(). Just trying to see what is the simplest way to create a test package without using a lot of other dependant packages etc.R007
Good approach! In that case base R and its package.skeleton() function should be your new best friends. I just found it a little off-putting that it would never pass R CMD check --as-cran immediately after creation, hence pkgKitten. But I use the same approach as you: try first with the minimal amount of helpers to reallly understand the minimal structure.Dirk Eddelbuettel
Actually, years ago I gave a workshop where we created each file by hand and you could look at the slides / check if it still holds: dirk.eddelbuettel.com/papers/r_package_development_nov2014.pdfDirk Eddelbuettel
There is no binary compilation, but I also found data.table sometimes needs extra care. Did you import() it in NAMESPACE? (And of course you should not have library() calls in R code in package. See what else R CMD check and/or the check button in RStudio say).Dirk Eddelbuettel

1 Answers

0
votes

Thanks @Dirk Eddelbuettel. You are right and it worked. I found out that question have been answered on StackOverflow and also good documentation available.

https://cran.r-project.org/web/packages/data.table/vignettes/datatable-importing.html

Using data.table package inside my own package