Is not writable error in install packages unable to install packages

I have this issue during package installation in R version 3.0.2 (2013-09-25) on an Ubuntu machine: install.packages("randomForest") Installing package into ‘/usr/local/lib/R/site-library’ (as ‘li...

I have this issue during package installation in R version 3.0.2 (2013-09-25) on an Ubuntu machine:

install.packages("randomForest")
Installing package into ‘/usr/local/lib/R/site-library’
(as ‘lib’ is unspecified)
Warning in install.packages :
  'lib = "/usr/local/lib/R/site-library"' is not writable

How to resolve it?

shadowtalker's user avatar

shadowtalker

11.8k3 gold badges47 silver badges91 bronze badges

asked Sep 12, 2015 at 10:17

Priya 's user avatar

2

For R version 3.2.2 (2015-08-14) this problem should be dealt with since R suggests within the installation process a different path to store your R libraries. The installation looks like this:
(Here ‘random’ is used as an example package)

install.packages('random')

Installing package into ‘/usr/local/lib/R/site-library’
(as ‘lib’ is unspecified)
Warning in install.packages("random") :
'lib = "/usr/local/lib/R/site-library"' is not writable

Would you like to use a personal library instead?  (y/n) y

Would you like to create a personal library
~/R/pc-linux-gnu-library/3.2
to install packages into?  (y/n) y

So during the installation answering both questions with ‘y’ should install the package correctly.

Update 18/01/19

In case you don’t want to store your R packages in an additional file:

As Antoine-Sac and Robert TheSim point out you can add yourself to the staff group in order to be able to write to ‘site-library’. (Click on the names to see their important additions)

Before this update I mentioned in this comment the option of changing the permission of the folder ‘site-library’ using ‘chmod o+w’ in order to be able to write to it. Assuming security issues but unable to tell at the time I warned about it but have primarily been waiting for somone to clear this up. Antoine-Sac and Robert TheSim have done so in the meantime. Thanks!

answered Apr 18, 2016 at 14:12

manuel_va's user avatar

manuel_vamanuel_va

9048 silver badges11 bronze badges

5

If you are on Windows, you can run R (or RStudio) as an administrator.

Close your R, then go to the R or RStudio icon, right-click and «open as administrator». It works perfectly, all error messages while installing packages are gone forever.

Gregor Thomas's user avatar

Gregor Thomas

130k18 gold badges160 silver badges286 bronze badges

answered Feb 23, 2018 at 22:20

Seyi's user avatar

SeyiSeyi

4233 silver badges11 bronze badges

4

add yourself to the group called ‘staff’

sudo usermod -a -G staff your_user_name

replace your_user_name with your login username, then logoff and relogin.

DO NOT use chmod 777 which is a breach of security and btw. a complete non-sense!!!

answered Jul 11, 2017 at 13:54

Robert TheSim's user avatar

8

For someone who tried to use install.packages() with multiple packages like this:

install.packages("vcd","vcdExtra","plyr")

and got similar warning:

Warning in install.packages :
  'lib = "vcdExtra"' is not writable
Would you like to use a personal library instead? (yes/No/cancel) cancel
Error in install.packages : unable to install packages

You should put the package names in a vector:

install.packages(c("vcd","vcdExtra","plyr"))

as the second parameter in install.packages() is lib.

answered Dec 11, 2018 at 15:41

BanAnanas's user avatar

BanAnanasBanAnanas

4517 silver badges16 bronze badges

8

The problem is that the default install location is a place where you do not have write permissions.

The solution is to use an install location where you do have write permissions.

Specifically, I’d suggest using the following commands to create a personal library folder in a place that doesn’t require special permissions and that will automatically be detected the next time you startup R:

dir.create(Sys.getenv("R_LIBS_USER"), recursive = TRUE)  # create personal library
.libPaths(Sys.getenv("R_LIBS_USER"))  # add to the path

install.packages("randomForest")  # install like always
library(randomForest)  # use library like always

The call to dir.create follows the suggestion in this faq to create a folder named according to Sys.getenv("R_LIBS_USER"). This is a good choice since it will be found on the next startup of R so you will be able to use install.packages and library without specifying special locations. The .libPaths function call lets us avoid restarting R by immediately adding the new folder to the library path. The first two lines are only needed if you do not yet have a personal library created, but there is no harm in running them repeatedly. After that, installing packages and using libraries can be done as usual.

answered May 17, 2019 at 17:38

teichert's user avatar

teichertteichert

3,6031 gold badge27 silver badges36 bronze badges

1

If you are using OS windows 10 then maybe Ransomware protection is on. You need to disable that.

I was facing the same problem. I had the access to write. but suddenly it stopped. I couldn’t install the packages. Disabling Ransomware protection worked for me.

mattliu's user avatar

mattliu

80515 silver badges28 bronze badges

answered Jun 26, 2019 at 19:44

Mohammed Sourav's user avatar

The "XX" is not writable error can also mean that the library path you’re providing does not exist.

answered Feb 11, 2022 at 12:33

Ljupcho Naumov's user avatar

Use sudo to Rscript code. I have same error fixed using sudo Rscript filename.R

Error

$ Rscript babynames.R 
Installing package into ‘/usr/local/lib/R/site-library’
(as ‘lib’ is unspecified)
Warning in install.packages("babynames") :
  'lib = "/usr/local/lib/R/site-library"' is not writable
Error in install.packages("babynames") : unable to install packages
Execution halted

Fix

$ sudo Rscript babynames.R 
[sudo] password for abhay: 
Installing package into ‘/usr/local/lib/R/site-library’
(as ‘lib’ is unspecified)
also installing the dependencies ‘cli’, ‘glue’, ‘utf8’, ‘fansi’, ‘lifecycle’, ‘magrittr’, ‘pillar’, ‘pkgconfig’, ‘rlang’, ‘vctrs’, ‘tibble’

answered Oct 15, 2022 at 2:48

iamabhaykmr's user avatar

iamabhaykmriamabhaykmr

1,6793 gold badges22 silver badges46 bronze badges

Maybe can try sudo chmod +777 #nameoflib
It works for me

answered Dec 1, 2022 at 5:09

Fish Ung's user avatar

You can change permission to ‘site-library’ and all included directories.

sudo chmod 777 -R /usr/local/lib/R/site-library

answered Jul 9, 2017 at 15:39

Igor Misechko's user avatar

2

If you are using R with RStudio, rather than starting RStudio with tray icon, start Rstudio or R with command line using sudo rstudio or sudo R.

It will solve your problem for sure, it works for me. It requires sudo privilege to write something in installation directory.

Scarabee's user avatar

Scarabee

5,3875 gold badges27 silver badges53 bronze badges

answered Feb 5, 2016 at 15:02

user3218971's user avatar

user3218971user3218971

5471 gold badge6 silver badges21 bronze badges

3

Содержание

  1. «not writable» error when installing new packages on 3.2.0 #144
  2. Comments
  3. R | Unable to Install Packages RStudio Issue (SOLUTION)
  4. Solution 1: Use R code to solve install.package()
  5. Solution 2: Use RStudio
  6. Conclusion
  7. 3 thoughts on “R | Unable to Install Packages RStudio Issue (SOLUTION)”
  8. Ошибки при установке R пакетов на Windows.
  9. package ‘foo’ is not available”
  10. unable to create temporary directory
  11. Found continuation line starting ‘ shortcut functio …’ at begin of record
  12. (converted from warning) installation of package ‘C:/Users/Alsey/AppData/Local/Temp/2/Rtmp4g880D/file259c11b85f00/vctrs_0.1.0.9003.tar.gz’ had non-zero exit status
  13. Warning Message: cannot remove prior installation of package ‘X’
  14. Unable to install packages in latest version of RStudio and R Version.3.1.1 [duplicate]
  15. 9 Answers 9
  16. Library is not writable
  17. 12 Answers 12

«not writable» error when installing new packages on 3.2.0 #144

I get an error when attempting to install packages:

The text was updated successfully, but these errors were encountered:

This is not a bug. As a normal user you would not have write access to anything in C:Program Files. When I try this, it prompts me to make a personal library.

If you want to install to the system library, you must run R or Rgui as administrator.

R windows FAQ documents this behavior:

http://cran.r-project.org/bin/windows/base/rw-FAQ.html
2.24 Does R run under Windows Vista/7/8/Server 2008?
.
If you install R as a standard user into your own file space and use it under the same account, there are no known permission issues.

If you use the default Administrator account (without ‘admin approval mode’ being turned on) and install/update packages (in the system area or elsewhere), no issues are known.

If you use an account in the local Administrators group in ‘admin approval mode’ (which is the intended norm under these OSes), installation will make use of ‘over-the-shoulder’ credentials. You will run into problems if you try installing (including updating) packages in the main R library. (It would be nice if at that point R could use over-the-shoulder credentials, but they apply to processes as a whole. Vista and later disallow creating .dll files in the system area without credentials.) There are several ways around this.

Run R with Administrator privileges in sessions where you want to install packages. (Do so by right-clicking on the R shortcut and selecting ’Run as Administrator’.)
Transfer ownership of the R installation to the user which installed R. To do so, use the security tab on the ‘Properties’ of the top-level R folder and give ‘Full Control’ over this directory to the user (not just the Administrator group).
Install packages into a different library tree owned by the account used to install R.
For an installation to be used by a single user, the simplest way is to make use of a ‘personal library’: See I don’t have permission to write to the R-3.2.0library directory.
.

Package installs work out-of-the-box in CRAN R 3.2.0, and the same must be true of RRO.

Источник

R | Unable to Install Packages RStudio Issue (SOLUTION)

Updated On January 16, 2022

If you are unable to install packages issue in R Studio, and facing any of the below mentioned error, you have landed on the right page:

Solution:

Solution 1: Use R code to solve install.package()

Use below command before using install.packages(“PACKAGE NAME”)

options(repos = c(CRAN = “http://cran.rstudio.com”))

Solution 2: Use RStudio

Changing the configuration in R Studio to solve install packages issue.

Go To Tools -> Global option -> Packages. Then uncheck the option “Use secure download method for HTTP”.

For other RStudio issues refer to official Troubleshooting Guide here.

Conclusion

I certainly hope that this guide will help people spend less time figuring about package install debugging and leave more time for data analysis and development.

Start your Data Science Journey here.

January 16, 2022

January 23, 2022

3 thoughts on “R | Unable to Install Packages RStudio Issue (SOLUTION)”

still unable to install any package on Rstudio. R version4.2.1.
> install.packages(“swirl”)
Warning in install.packages :
unable to access index for repository http://cran.rstudio.com/src/contrib:
cannot open URL ‘http://cran.rstudio.com/src/contrib/PACKAGES’
Installing package into ‘C:/Users/Alka/AppData/Local/R/win-library/4.2’
(as ‘lib’ is unspecified)
Warning in install.packages :
unable to access index for repository http://cran.rstudio.com/src/contrib:
cannot open URL ‘http://cran.rstudio.com/src/contrib/PACKAGES’
Warning in install.packages :
package ‘swirl’ is not available for this version of R

A version of this package for your version of R might be available elsewhere,
see the ideas at
https://cran.r-project.org/doc/manuals/r-patched/R-admin.html#Installing-packages
Warning in install.packages :
unable to access index for repository http://cran.rstudio.com/bin/windows/contrib/4.2:
cannot open URL ‘http://cran.rstudio.com/bin/windows/contrib/4.2/PACKAGES’

Do you know why this needs to be done? it is working fine now – thanks for the help. But may I know the reason behind it?

Источник

Ошибки при установке R пакетов на Windows.

В большинстве случаев, особенно при установке пакетов из CRAN никаких проблем не возникает, но периодически всё таки вы можете столкнуться с некоторыми ошибками.

В этой статье я со временем буду добавлять материал с описанием различных ошибок которые возникают при установке пакетов.

package ‘foo’ is not available”

Достаточно распространённая ошибка, текст которой к сожалению не сообщает о реальной проблеме, которой была эта ошибка вызвана.

В одной из статей на RBloggers, автор опубликовал подробный чек лист как с этой ошибкой бороться.

  1. Неправильно написанное название пакета. Первое, что стоит проверить — это правильно ли вы написали название пакета, который хотите установить. R регистро чувствительный язык, поэтому даже одна буква написанная не в том регистре будет считаться неправильным именем пакета. Лучший способ копировать название пакета из CRAN.
  2. Проверьте своё интернет соединение. Звучит банально, но иногда в процессе разработки когда мы можем не заметить, что уже более часа работаем без доступа к интернету.
  3. Проверьте сеть CRAN. Возможно в момент установки пакета не доступны сервера CRAN, для проверки просто попробуйте загрузить главный сайт проекта. Если основное зеркало CRAN не доступно, вы можете установить пакет из другого, используя аргумент repos внутри функции install.packages() .
  4. Убедитесь в том, что пакет был опубликован на CRAN. Перед тем как пакет попадёт на CRAN, зачастую автор проводит большую работу над его тестированием, и доработкой функционала. Как правило на CRAN публикуются пакеты чей код и функционал уже устоялся, и считался стабильным. Поэтому 4ый шаг, просто убедитесь в том, что нужный пакет уже опубликван. Если пакета нет на CRAN, то скорее всего вы можете найти его на GitHub, и установить с помощью команды devtools::install_github(‘pkg_name’) .
  5. Убедитесь в том, что пакет не был удалён из CRAN. Требования политики публикации пакетов в CRAN не редко меняются, если автор перестал поддерживать свой пакет, и с течением времени этот пакет стал нарушать правила политики публикации CRAN, то его удалят из репозитория. В таком случае перейдя на страницу пакета https://cran.r-project.org/package=PACKAGE_NAME, вы увидите сообщение “Package ‘foo’ was removed from the CRAN repository.”, что и свидетельствует об удалении пакета из CRAN. Если вы получите ошибку 404, значит пакет ранее не был опубликован на CRAN.

unable to create temporary directory

Недавно столкнулся с проблемой при установке пакетов из RStudio — ОШИБКА: нет прав для установочной папки ‘C:/Users/Documents/R/win-library/3.5’.

Та же ошибка может возвращать и следующие сообщения:

  • ‘lib = «C:/Users/Alsey/Documents/R/win-library/3.5″‘ is not writable
  • Error in install.packages : unable to create temporary directory ‘C:UsersAlseyDocumentsRwin-library3.5file34ac62294fbd’

С чем связано её появление я так и не понял, но устранить получилось следующим образом:

  1. Создайте новую папку, которая будет в последствии вашей пользовательской библиотекой R пакетов, лучше создавать её не на диске C, что бы в последствии не сталкиваться с такой же проблемой.
  2. В основной вашей рабочей директории (скорее всего это папка ‘Документы’ которая обычно находится в каталоге пользователя Windows, примерный путь к ней C:UsersAlseyDocuments ), найдите файл .Renviron, на данный момент он будет пустой, это файл конфигурации R, именно в нём можно менять дефолтные значения глобальных переменных R, вам необходимо в него вписать одну строку R_LIBS_USER=D:/r_library, где D:/r_library это путь к созданной на первом шаге папке.
  3. Далее перезапустите сессию R, и можете убедиться с помощью команды .libPaths() , что созданная на первом шаге папка стала пользовательской библиотекой для установки и хранения пакетов.

Could not find tools necessary to compile a package

С этой ошибкой я столкнулся при установке пакетов из GitHub после обновления R до более новой версии.

Ответ я нашел вот тут.

Проблема возникает при попытке RStudio проверить установленные у вас инструменты сборки пакетов, для того, что бы подвить эту проверку необходимо перед установкой пакета установить следующую опцию.

После чего можно устанавливать пакет.

Found continuation line starting ‘ shortcut functio …’ at begin of record

Эта проблема появилась при установке пакетов из GitHub с помоью devtools не так давно, и связана она с файлом DESCRIPTION.

Возникает в ситуации когда в файле DESCRIPTION имеется многострочное описание в поле » Description: «.

Для исправления вам необходимо форкнуть нужный пакет на GitHub.

Создать свою ветку пакета на GitHub

И сделать однострочным поле » Description: » в файле DESCRIPTION, далее устанавливайте пакет уже из своего репозитория.

(converted from warning) installation of package ‘C:/Users/Alsey/AppData/Local/Temp/2/Rtmp4g880D/file259c11b85f00/vctrs_0.1.0.9003.tar.gz’ had non-zero exit status

Вызвана данная ошибка конфликтом возникающим при установке пакетов одновременно для разных версий ядра R, 32 и 64 битных.

Полный текст ошибки из консоли:

Узнать разрядность версии R в которой вы работаете можно двумя способами:

В случае если вы используете 32 битный R вернётся значение «/i386» .

На 32 битном R вы получите «x86_32» .

После того, как мы определили разрядность ядра требуется пойти одним из описанных способов, для 64 битной версии просто используйте при установке пакета опцию «—no-multiarch».

Если у вас 32 битная версия, то необходимо изменить в переменной окружения PATH путь к утилите RTools с C:Rtoolsmingw_64bin на C:Rtoolsmingw_32bin . О том как это сделать можно узнать в этой статье .

Далее запускаем установку пакета только для 32 битной версии с помощью опции «—no-multiarch» , так же как и ранее было показано с примером для 64 разрядного R.

Warning Message: cannot remove prior installation of package ‘X’

Если вы увидели такое сообщение при попытке установить какой-либо пакет, это говорит о том, что пакет в данный момент заблокирован каким – то процессом. Первое, что вам необходимо попробовать сделать это перезапустить RStudio, и попробовать повторно запустить установку пакета.

Если перезапуск RStudio не помог, то откройте диспетчер задач, и на вкладке подробности посмотрите, нет ли у вас каких либо зависших R сеансов.

Если такие есть их необходимо завершить, и попробовать повторно запустить процесс установки пакета.

Если и это не помогло, то идём третьим способом.

  1. Найдите путь к папкам, в которых у вас установлены пакеты, делается это командой .libPaths() .
  2. В ручном режиме удалите папку с пакетом, который пытаетесь установить.
  3. Откройте RStudio и повторите попытку установить пакет.

Один из перечисленных выше способов должен сработать.

Статья будет постоянно дополняться, дата последнего редактирования 6 октября 2020 года.

Источник

Unable to install packages in latest version of RStudio and R Version.3.1.1 [duplicate]

I am unable to install packages through latest version of RStudio and R Version.3.1.1. Kindly help. I got the error as mentioned below:

9 Answers 9

Not 100% certain that you have the same problem, but I found out the hard way that my job blocks each mirror site option that was offered and I was getting errors like this:

Workaround (I am using CentOS).

I hope this saves someone hours of frustration.

I think this is the «set it and forget it» solution:

Note that this isn’t https. I was on a Linux machine, ssh’ing in. If I used https, it didn’t work.

As @Pascal said, it is likely that you encounter problem with the firewall or/and proxy issue. As a first step, go through FAQ on the CRAN web page. After that, try to flag R with —internet2.

Sometimes it could be useful to check global options in R studio and uncheck «Use Internet Explorer library/proxy for HTTP». Tools -> Global Options -> Packages and unchecking the «Use Internet Explorer library/proxy for HTTP» option.

Hope this helps.

Based on answers from the community, there appear to be several ways that might solve this:

Источник

Library is not writable

I have this issue during package installation in R version 3.0.2 (2013-09-25) on an Ubuntu machine:

How to resolve it?

12 Answers 12

For R version 3.2.2 (2015-08-14) this problem should be dealt with since R suggests within the installation process a different path to store your R libraries. The installation looks like this: (Here ‘random’ is used as an example package)

So during the installation answering both questions with ‘y’ should install the package correctly.

Update 18/01/19

In case you don’t want to store your R packages in an additional file:

As Antoine-Sac and Robert TheSim point out you can add yourself to the staff group in order to be able to write to ‘site-library’. (Click on the names to see their important additions)

Before this update I mentioned in this comment the option of changing the permission of the folder ‘site-library’ using ‘chmod o+w’ in order to be able to write to it. Assuming security issues but unable to tell at the time I warned about it but have primarily been waiting for somone to clear this up. Antoine-Sac and Robert TheSim have done so in the meantime. Thanks!

add yourself to the group called ‘staff’

replace your_user_name with your login username, then logoff and relogin.

DO NOT use chmod 777 which is a breach of security and btw. a complete non-sense.

If you are on Windows, you can run R (or RStudio) as an administrator.

Close your R, then go to the R or RStudio icon, right-click and «open as administrator». It works perfectly, all error messages while installing packages are gone forever.

For someone who tried to use install.packages() with multiple packages like this:

and got similar warning:

You should put the package names in a vector:

as the second parameter in install.packages() is lib.

The problem is that the default install location is a place where you do not have write permissions.

The solution is to use an install location where you do have write permissions.

Specifically, I’d suggest using the following commands to create a personal library folder in a place that doesn’t require special permissions and that will automatically be detected the next time you startup R:

Источник

В большинстве случаев, особенно при установке пакетов из CRAN никаких проблем не возникает, но периодически всё таки вы можете столкнуться с некоторыми ошибками.

В этой статье я со временем буду добавлять материал с описанием различных ошибок которые возникают при установке пакетов.

package ‘foo’ is not available”

Достаточно распространённая ошибка, текст которой к сожалению не сообщает о реальной проблеме, которой была эта ошибка вызвана.

В одной из статей на RBloggers, автор опубликовал подробный чек лист как с этой ошибкой бороться.

  1. Неправильно написанное название пакета. Первое, что стоит проверить — это правильно ли вы написали название пакета, который хотите установить. R регистро чувствительный язык, поэтому даже одна буква написанная не в том регистре будет считаться неправильным именем пакета. Лучший способ копировать название пакета из CRAN.
  2. Проверьте своё интернет соединение. Звучит банально, но иногда в процессе разработки когда мы можем не заметить, что уже более часа работаем без доступа к интернету.
  3. Проверьте сеть CRAN. Возможно в момент установки пакета не доступны сервера CRAN, для проверки просто попробуйте загрузить главный сайт проекта. Если основное зеркало CRAN не доступно, вы можете установить пакет из другого, используя аргумент repos внутри функции install.packages().
  4. Убедитесь в том, что пакет был опубликован на CRAN. Перед тем как пакет попадёт на CRAN, зачастую автор проводит большую работу над его тестированием, и доработкой функционала. Как правило на CRAN публикуются пакеты чей код и функционал уже устоялся, и считался стабильным. Поэтому 4ый шаг, просто убедитесь в том, что нужный пакет уже опубликван. Если пакета нет на CRAN, то скорее всего вы можете найти его на GitHub, и установить с помощью команды devtools::install_github('pkg_name').
  5. Убедитесь в том, что пакет не был удалён из CRAN. Требования политики публикации пакетов в CRAN не редко меняются, если автор перестал поддерживать свой пакет, и с течением времени этот пакет стал нарушать правила политики публикации CRAN, то его удалят из репозитория. В таком случае перейдя на страницу пакета https://cran.r-project.org/package=PACKAGE_NAME, вы увидите сообщение “Package ‘foo’ was removed from the CRAN repository.”, что и свидетельствует об удалении пакета из CRAN. Если вы получите ошибку 404, значит пакет ранее не был опубликован на CRAN.

unable to create temporary directory

Недавно столкнулся с проблемой при установке пакетов из RStudio — ОШИБКА: нет прав для установочной папки ‘C:/Users/Documents/R/win-library/3.5’.

Та же ошибка может возвращать и следующие сообщения:

  • ‘lib = «C:/Users/Alsey/Documents/R/win-library/3.5″‘ is not writable
  • Error in install.packages : unable to create temporary directory ‘C:UsersAlseyDocumentsRwin-library3.5file34ac62294fbd’

С чем связано её появление я так и не понял, но устранить получилось следующим образом:

  1. Создайте новую папку, которая будет в последствии вашей пользовательской библиотекой R пакетов, лучше создавать её не на диске C, что бы в последствии не сталкиваться с такой же проблемой.
  2. В основной вашей рабочей директории (скорее всего это папка ‘Документы’ которая обычно находится в каталоге пользователя Windows, примерный путь к ней C:UsersAlseyDocuments ), найдите файл .Renviron, на данный момент он будет пустой, это файл конфигурации R, именно в нём можно менять дефолтные значения глобальных переменных R, вам необходимо в него вписать одну строку  R_LIBS_USER=D:/r_library, где D:/r_library это путь к созданной на первом шаге папке.
  3. Далее перезапустите сессию R, и можете убедиться с помощью команды .libPaths(), что созданная на первом шаге папка стала пользовательской библиотекой для установки и хранения пакетов.

Could not find tools necessary to compile a package

С этой ошибкой я столкнулся при установке пакетов из GitHub после обновления R до более новой версии.

Ответ я нашел вот тут.

Проблема возникает при попытке RStudio проверить установленные у вас инструменты сборки пакетов, для того, что бы подвить эту проверку необходимо перед установкой пакета установить следующую опцию.

options(buildtools.check = function(action) TRUE )

После чего можно устанавливать пакет.

Found continuation line starting ‘ shortcut functio …’ at begin of record

Эта проблема появилась при установке пакетов из GitHub с помоью devtools не так давно, и связана она с файлом DESCRIPTION.

Возникает в ситуации когда в файле DESCRIPTION имеется многострочное описание в поле » Description: «.

Для исправления вам необходимо форкнуть нужный пакет на GitHub.

Создать свою ветку пакета на GitHub

И сделать однострочным поле » Description: » в файле DESCRIPTION, далее устанавливайте пакет уже из своего репозитория.

(converted from warning) installation of package ‘C:/Users/Alsey/AppData/Local/Temp/2/Rtmp4g880D/file259c11b85f00/vctrs_0.1.0.9003.tar.gz’ had non-zero exit status

Вызвана данная ошибка конфликтом возникающим при установке пакетов одновременно для разных версий ядра R, 32 и 64 битных.

Полный текст ошибки из консоли:

error: ld returned 1 exit status
no DLL was created
ERROR: compilation failed for package 'vctrs'
* removing 'D:/r_library/vctrs'
* restoring previous 'D:/r_library/vctrs'
Error in i.p(...) : 
  (converted from warning) installation of package ‘C:/Users/Alsey/AppData/Local/Temp/Rtmpyu30Ew/file35cc2a261c8f/vctrs_0.2.0.9000.tar.gz’ had non-zero exit status

Узнать разрядность версии R в которой вы работаете можно двумя способами:

Sys.getenv("R_ARCH")
[1] "/x64"

В случае если вы используете 32 битный R вернётся значение "/i386".

Sys.info()[["machine"]]
[1] "x86-64"

На 32 битном R вы получите "x86_32".

После того, как мы определили разрядность ядра требуется пойти одним из описанных способов, для 64 битной версии просто используйте при установке пакета опцию "--no-multiarch".

devtools::install_github("username/repos", INSTALL_opts = "--no-multiarch")

Если у вас 32 битная версия, то необходимо изменить в переменной окружения PATH путь к утилите RTools с C:Rtoolsmingw_64bin на C:Rtoolsmingw_32bin. О том как это сделать можно узнать в этой статье .

Далее запускаем установку пакета только для 32 битной версии с помощью опции "--no-multiarch", так же как и ранее было показано с примером для 64 разрядного R.

Warning Message: cannot remove prior installation of package ‘X’

Если вы увидели такое сообщение при попытке установить какой-либо пакет, это говорит о том, что пакет в данный момент заблокирован каким – то процессом. Первое, что вам необходимо попробовать сделать это перезапустить RStudio, и попробовать повторно запустить установку пакета.

Если перезапуск RStudio не помог, то откройте диспетчер задач, и на вкладке подробности посмотрите, нет ли у вас каких либо зависших R сеансов.

Если такие есть их необходимо завершить, и попробовать повторно запустить процесс установки пакета.

Если и это не помогло, то идём третьим способом.

  1. Найдите путь к папкам, в которых у вас установлены пакеты, делается это командой .libPaths().
  2. В ручном режиме удалите папку с пакетом, который пытаетесь установить.
  3. Откройте RStudio и повторите попытку установить пакет.

Один из перечисленных выше способов должен сработать.


Статья будет постоянно дополняться, дата последнего редактирования 6 октября 2020 года.

Unable to Install packages in R

@6b1a06c4

Last seen 17 months ago

Canada

R version 4.1.1 (2021-08-10) -- "Kick Things"
Copyright (C) 2021 The R Foundation for Statistical Computing
Platform: x86_64-w64-mingw32/x64 (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

> install.packages("Rcmdr")
Warning in install.packages :
  'lib = "C:/Program Files/R/R-4.1.1/library"' is not writable
Error in install.packages : unable to install packages
Making 'packages.html' ... done

rstudio

• 1.5k views

@james-w-macdonald-5106

Last seen 2 hours ago

United States

This support site is intended to help people with Bioconductor packages, and Rcmdr is a CRAN package. In future you should ask about CRAN packages on r-help@r-project.org.

That said, the default library directory on Windows is not writeable by a regular user, and when you try to install packages you should get a message asking if you would like to use a personal library instead. You should say ‘Yes’ to that, otherwise you won’t be able to install any packages.

Login before adding your answer.

[This article was first published on R on Andres’ Blog, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)


Want to share your content on R-bloggers? click here if you have a blog, or here if you don’t.

For reasonably experienced R users this simple topic might not seem worthy of a blog post, so if you are not an R beginner, you may want to skip this post. Having that said, I have had to explain this task so many times on R community forums that writing one becomes mandatory to avoid typing the same text yet once again.

The reasons to customize your library path instead of going with the defaults could be varied, but for R beginners the most common one is to avoid package installation problems due to write permissions, non-ASCII characters on folder paths, cloud-synced folders, or network drives, which lead into error messages such as:

Warning in install.packages :
  'lib = "/path/to/your/library"' is not writable
Error in install.packages : unable to install packages
** byte-compile and prepare package for lazy loading
Error: unexpected symbol in "setwd('incomplete/path/to/your/library"
Execution halted

Very often, the solution for these issues is to set your package library somewhere else in your system, where you have proper permissions and there are no known R incompatibilities. The way to change a package library location is to manually set it on a startup file i.e. Rprofile.site and Renviron.site files for R-version level (located at R_HOME/etc/) or .Rprofile and .Renviron files, for user-level (located at your HOME folder) or project-level (located at the current working directory).

✏ For more information about R startup files, you can read the following support article.

For Renviron type files, the corresponding environmental variable must be specified, for example, if I want to change the R library trees on a Linux system I would add a line like this to the Renviron.site file located at /usr/lib/R/etc/ (On this case the R_HOME environmental variable gets translated to /usr/lib/R/).

R_LIBS_SITE="/usr/lib/R/site-library:/usr/lib/R/library"

Being the first location from the left the default one, which gets used by install.packages() if the lib argument is not specified, and all of them (which are colon-separated) are scanned for packages at startup in order. Have in mind that only directories that exist at the time will be included.

For Rprofile type files, the .libPaths() function must be used, since these files must contain valid R code to be executed at startup, the equivalent R command to the previous example would be:

.libPaths(c("/usr/lib/R/site-library", "/usr/lib/R/library"))

Obviously, the folder paths are going to be different depending on your specific operating system and setup, but I hope you get the general idea that you have to specify a folder path that is suitable for your specific needs, for example, on a Windows system the equivalent would be:

.libPaths(c("C:/Program Files/R/R-4.0.3/library"))

By default, the default package-library is set at the user-level (HOME folder), which, in some cases, can cause the aforementioned issues. Now, this is opinionated advice, but for simple individual use, I find it more practical to set the default package-library at R-version level (R_HOME/library/ folder) and explicitly make use of other locations, selectively, and accordingly to specific use cases. Be aware that depending on your security settings and operating system, you might need to run your R session with “administrator” rights or from a user with “sudo” rights in order for this to work.

Понравилась статья? Поделить с друзьями:
  • Is not in sudoers file debian как исправить
  • Is not defined python как исправить
  • Is not a valid win32 application как исправить
  • Is not a valid floating point value как исправить
  • Is not a valid date как исправить