Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including R scripts in R packages

I want to share some software as a package but some of my scripts do not seem to go very naturally as functions. For example consider the following chunk of code where 'raw.df' is a data frame containing variables of both discrete and continuous kinds. The functions 'count.unique' and 'squash' will be defined in the package. The script splits the data frame into two frames, 'cat.df' to be treated as categorical data and 'cts.df' to be treated as continuous data.

My idea of how this would be used is that the user would read in the data frame 'raw.df', source the script, then interactively edit 'cat.df' and 'cts.df', perhaps combining some categories and transforming some variables.

dcutoff <- 9
tail(raw.df)
(nvals <- apply(raw.df, 2, count.unique))
p <- dim(raw.df)[2]
(catvar <- (1:p)[nvals <= dcutoff])
p.cat <- length(catvar)
(ctsvar <- (1:p)[nvals > dcutoff])
p.cts <- length(ctsvar)
cat.df <- raw.df[ ,catvar]
for (i in 1:p.cat) cat.df[ ,i] <- squash(cat.df[ ,i])
head(cat.df)
for(i in 1:p.cat) {
    cat(as.vector(table(cat.df[ ,i])), "\n")
}    
cts.df <- raw.df[ ,ctsvar]
for(i in 1:p.cts) {
    cat( quantile(cts.df[ ,i], probs = seq(0, 1, 0.1)), "\n")
}

Now this could, of course, be made into a function returning a list containing nvals, p, p.cat, cat.df, etc; however this seems rather ugly to me. However the only provision for including scripts in a package seems to be the 'demo' folder which does not seem to be the right way to go. Advice on how to proceed would be gratefully received.

(But the gratitude would not be formally expressed as it seems that using a comment to express thanks is deprecated.)

like image 869
Murray Jorgensen Avatar asked Sep 30 '22 18:09

Murray Jorgensen


1 Answers

It is better to encapsulate your code in a function. It is not ugly to return a list, S3 objects for example are just a list with an attribute class.

object <- list(attribute.name = something, ..)
class(object) <- "cname"
return (object)

You can also use inst folder (as mentioned in Dirk comment) since the contents of the inst subdirectory will be copied recursively to the installation directory.

  1. you create an inst folder:

    inst
    ----scripts
        some_scripts.R
    
  2. You can call it from a function in your package and use system.file mechanism to load it.

    load_myscript <- function(){
      source(system.file(package='your_pkg_name','scripts/some_scripts.R'))
    }
    
  3. You call it as any other function in your package:

    load_myscript()
    
like image 182
agstudy Avatar answered Oct 03 '22 00:10

agstudy