Skip to content

Library is not writable [SOLUTION]

Mattan S. Ben-Shachar edited this page May 27, 2020 · 3 revisions

When trying to install a package you get the an error similar to this:

Warning in install.packages :
  'lib = "<some library path>"' is not writable
Warning in install.packages :
  Cannot create dir '<path>\?????', reason 'Invalid argument'
Error in install.packages : unable to create '<path>\?????'

Why does this happen?

Seems like you don't have writing permissions to the default folder, and R is not able to create a new folder - possible due to the default path having non ASCII letters? (This happens to my students with Hebrew paths.)

How to solve

This solution is based on this awesome guide.

  1. Create a folder

This is where packages will be installed, so make sure you put is somewhere where it won't accidentally get deleted.
It should also be comprised of only base English letters.
Suggestion: Folder R_PKGS in C:.

  1. Open R / Rstudio as admin

  2. Run in R console

file.edit(file.path(R.home(component = "home"), "library", "base", "R", "Rprofile"))

This should open a file names Rprofile. Scroll to the bottom of it.

  1. Add the following code to the bottom
#### MSB ####
{
  # WHERE TO SAVE?
  pkg_install_dir <- "<REPLACE ME WITH THE NEW PATH>"
  
  if (.libPaths()[1] != pkg_install_dir) {
    # DOES THE FOLDER EXIST?
    if (pid_not_exist <- !file.exists(pkg_install_dir))
      warning(pkg_install_dir, " directory does not exist.")
    
    # IS THE FOLDER WRITABLE
    if (!pid_not_exist && (pid_not_write <- file.access(pkg_install_dir, mode = 2)))
      warning("Cannot write to", pkg_install_dir, ". Are you admin?")
    
    # change file order
    if (!pid_not_exist && !pid_not_write) {
      .libPaths(unique(c(pkg_install_dir, .libPaths())))
      cat("NOTE: Added ", pkg_install_dir, " to .libPaths(), as your default pkg installation folder.\n")
      cat("NOTE: This may not work when updating or fresh-installing R.\n\n")
    }
  }
}
#### \MSB ####

And replace <REPLACE ME WITH THE NEW PATH> with the full path to the new folder.

  1. Save (ctrl + S) and close R / Rstudio.

  2. Open R / Rstudio

You should see in the console a message telling you that you path has been added as the default installation path.

  1. Install a package

It should work 🤷‍♂️

Clone this wiki locally