1

The following commands work fine in RStudio, but not RScript:

require(glmnet)
calibdata = read.csv("calibrationfile.csv")

xs = model.matrix(as.formula("targetvar~predictor1+predictor2)),calibdata)[,-1] # -1 discards intercept constant, glmnet has its own
ys = as.numeric(unlist(calibdata["targetvar"]))
fit=cv.glmnet(xs,ys)

The error message from RScript:

Error in is(x, "CsparseMatrix") : could not find function "new"
Calls: cv.glmnet -> glmnet -> elnet -> getcoef -> drop0 -> is
Execution halted

R version is 3.2.3 in both cases and glmnet version 2.0-2.

How can I get glmnet to work in RScript?

Sideshow Bob
  • 4,566
  • 5
  • 42
  • 79
  • Should this perhaps be migrated to Stack Overflow? It does not seem to be on-topic here, so I don't think it should be reopened, but I wonder if it would benefit from migration. – Silverfish Dec 15 '15 at 18:28

2 Answers2

6

RScript has this "lovely" feature of not loading the (base package) methods for you.

So all you need here is an additional

  require(methods)

or

  suppressMessages(library(methods))

For what it is worth, the littler command-line and scripting front-end to R that Jeff Horner and I wrote defaults to loading methods for you...

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • I met exactly the same problem. Script ran normally untill I did an update to the kernel of the system. it works fine now. Thanks Dirk. – ZFY Feb 22 '17 at 13:15
0

I ran into same issue, and found two possible workaround (just for a complement of @Dirk Eddelbuettel's answer):

Well, I read somewhere that --default-packages=methods,utils needs to be passed to Rscript to work around this: https://github.com/stan-dev/rstan/issues/190

OR,

Also, it seems, Rscript being missing the load of the methods package. This can also be fixed by calling library('methods') at the beginning of your script: https://github.com/dhimmel/elevcan/issues/1.

Hope this helps.

Gauthier Boaglio
  • 10,054
  • 5
  • 48
  • 85