2

I tried several ways on loading few specific packages inside my script.R to run the script in terminal by typing ./Rscript script.R. There is no problem with the script but I get an error when I want to load a package e,g tidyverse.

Error: package or namespace load failed for ‘tidyverse’ in rbind(info, getNamespaceInfo(env, "S3methods")):
number of columns of matrices must match (see arg 2)
In addition: Warning message:
package ‘tidyverse’ was built under R version 3.6.0

Based on this link Installing a package in R inside a script I tried to find the location of the library by typing .libPaths() in Rstudio then I gave the path to load the package inside the script.R by typing library(tidyverse,lib.loc="/Library/Frameworks/R.framework/Versions/3.6/Resources/library")

Again I get the same error. Could you please mention where is the mistake happening? Thanks

Apex
  • 1,055
  • 4
  • 22
  • This might be of help - https://www.researchgate.net/post/How_can_I_load_packages_from_an_R_script_using_R_CMD_BATCH_via_the_command_prompt - among other options, they suggest making your own code a package so that it calls dependencies by itself. – Pablo Herreros Cantis May 05 '20 at 14:16
  • Also, do you get that same problem with any other package, or is ```tidyverse``` the only one? – Pablo Herreros Cantis May 05 '20 at 14:18
  • 1
    You might also see if ```require()``` has the same result. You can find a script that uses require and checks whether it was successful here - https://yihui.org/en/2014/07/library-vs-require: ```if (require('foo')) { awesome_foo_function() } else { warning('You missed an awesome function') }``` – Pablo Herreros Cantis May 05 '20 at 14:20
  • 1
    @PabloHerrerosCantis I tried with ```readr``` and I still get the same error – Apex May 05 '20 at 14:20

2 Answers2

1

Note that it is not recommended to use require() to load packages. If using library() fails, there's no reason why require() would work.

From your question, it looks like you're using a certain Rscript binary in your current folder (./Rscript), this might not be using the same version of R as RStudio is doing.

You could try running

Rscript -e "library(tidyverse)"

to see if you can load tidyverse. Note that I'm using the Rscript command here instead of ./Rscript. This should point to your latest R version installed and the same one RStudio is using.

If the error persists, you could just try re-installing tidyverse using

Rscript -e "install.packages('tidyverse')"
milanmlft
  • 411
  • 3
  • 14
0

The solution is loading the package by require()

require(dplyr)
Apex
  • 1,055
  • 4
  • 22