Как обновить r studio
Перейти к содержимому

Как обновить r studio

  • автор:

R-bloggers

R news and tutorials contributed by hundreds of R bloggers

How to install (and update!) R and RStudio

Posted on January 1, 2022 by R on R (for ecology) in R bloggers | 0 Comments

One of the first steps to learning R is to have it downloaded and installed on your computer. In this post I’ll show you how to do that and how to download and install RStudio—a key tool for using R, and how I do all my work and tutorials.

If you want to follow along with a video tutorial, you can click on the image below where you can watch the first lesson in my full course on the Basics of R (for ecologists).

Video thumbnail for how to install R and Rstudio

For starters, R is a free open-source programming language used for organizing, analyzing, and visualizing data. Its versatility is highlighted by the large number of user-created packages that it comes with, which provide useful functions and guides that anyone can use (e.g., found on CRAN). So R is the programming language itself, and it comes with an environment or console that can read and execute your code. You could code in R without using RStudio, as you can see in the image below. That’s what the plain R console looks like; I just loaded up some data, viewed the first few rows, and renamed the columns.

Image showing the plain R console, with the trees dataset loaded up

By comparison, RStudio is a more versatile IDE, or Integrated Development Environment. Most people who use R also use RStudio because it provides a clean point-and-click dashboard of tools where you can type your code, view your figures, organize your data, variables, and files, as well as viewing the help window. In comparison to RStudio, the basic R IDE/console is extremely basic and doesn’t provide as many accessible tools as RStudio does.

Image showing the RStudio console and its greater complexity and number of tools

If you are installing R and RStudio for the first time:

To download R, go here. Choose the download link that corresponds to your computer. I have a Mac, so I clicked that link.

Image showing download options for R.

You can download RStudio here, and you want to choose “RStudio Desktop”.

The important thing when installing R and RStudio is that you need to install R before you install RStudio. If you do it in the reverse order, you will likely run into errors. All you’ll need to do is open the files you downloaded for R and RStudio, and the installation process should begin on its own.

For Mac users, there’s also something called XQuartz, which you might not need for basic coding in R, but which might be helpful down the line for running certain packages. You can download XQuartz here. Similarly, if you just open the downloaded file, XQuartz should install on its own.

If you want to update R and RStudio:

There are a few ways you can check your version of R and see whether or not it needs to be updated. One way is to run the actual R program. There, you can go to the “R” menu and click “Check for R Updates” (see image below). If you do that, R will tell you the current version you’re on, and whether or not there is a more updated version that you can download (circled in blue).

Alternatively, if you’re in RStudio, you can type and run “sessionInfo()” in the R Console. The first line that the console returns is the version of R that you’re using. You can then download and install the latest version of R here for Mac, and here for Windows.

If you’re using a Windows computer, you may need to uninstall R to update it. You can find a quick guide for that here. Another great option for Windows users is to use a package called installr (unfortunately only available for Windows, @Mac users). All you need to do is install “installr”, load up the library, and run the code “updateR()”. This function will check for newer versions and will guide you through the update process.

Image showing cursor hovering over the R menu and Check for R Updates. The text also shows the version of R that the user is on, and it shows that they need to update their R software.

If you want to update to the latest version of RStudio, hover over “Help” on the top menu bar of your Mac, and click “Check for Updates”. Then, quit the RStudio program, go to the RStudio website, and download and install the latest version. Image showing a cursor mousing over “Help” on the top menu bar and “Check for Updates”Now you should have the latest versions of R and RStudio on your computer. I hope this tutorial was helpful!

If you liked this post and want to learn more, then check out my online course on the complete basics of R for ecology:

Also be sure to check out R-bloggers for other great tutorials on learning R

R Language
Обновление версии R

Установка или обновление вашего ПО даст доступ к новым функциям и исправлениям ошибок. Обновление вашей установки R можно выполнить несколькими способами. Один простой способ — перейти на сайт R и загрузить последнюю версию для вашей системы.

Установка с сайта R

Чтобы получить последнюю версию, перейдите на страницу https://cran.r-project.org/ и загрузите файл для своей операционной системы. Откройте загруженный файл и следуйте инструкциям на экране. Все настройки можно оставить по умолчанию, если вы не хотите изменить определенное поведение.

Обновление из R с помощью пакета installr

Вы также можете обновить R из R, используя удобный пакет под названием installr .

Open R Console (НЕ RStudio, это не работает из RStudio) и выполните следующий код, чтобы установить пакет и инициировать обновление.

введите описание изображения здесь

Выбор старых пакетов

По завершении установки нажмите кнопку «Готово».

Теперь он спрашивает, хотите ли вы скопировать свои пакеты из старой версии R в более новую версию R. Как только вы выберете да, весь пакет будет скопирован в более новую версию R.

введите описание изображения здесь

После этого вы можете выбрать, хотите ли вы сохранить старые пакеты или удалить.

Наиболее простой способ обновить язык R (пакет installr)

Несколько раз в год выходят обновления для языка R, примерно раз в пол года выходят достаточно важные обновления.

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

Почему просто не скачать и установить новую версию

В принципе процесс обновления не сложный, по сути достаточно скачать и установить новую версию, но проблемы начинаются тогда, когда вы понимаете, что вам по новому надо устанавливать все пакеты.

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

К счастью, на самом деле в R есть пакет на любой случай жизни, в том числе и для обновления самого R есть пакет, называется он installr.

Прелесть пакета заключается в том, что он позволяет перенести все установленные ранее пакеты в новую версию R.

Как обновить R через пакет installr

Ниже я приведу вам пошаговое руководство по наиболее быстрому способу обновления языка R до наиболее актуальной версии.

Для тех, кому лень читать текст вот небольшой видео мануал:

Все описанные ниже действия рекомендуется выполнять в интерфейсе RGui, а не в привычной для многих среде разработки RStudio.

Обычно, на windows ярлык RGui находится по адресу C:\Program Files\R\R-3.5.1\bin\x64\Rgui.exe

Для начала необходимо установить пакет с помощью стандартной команды install.packages(«installr») .

Далее подключаем пакет library(installr) и запускаем команду updateR() .

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

Диалоговое окно отображающее версию R

Жмём OK, и видим следующее диалоговое окно.

Хотите ли вы прочитать файл новостей новой версии R.

На самом деле неважно, что вы ответите, после чего откроется следующее окно, в котором вас спрашивают установить последнюю версию R?

Вы хотите установить последнюю версию R?
Прогрессбар процесса скачивания версии R.

Далее начнётся обычный процесс установки R.

Процесс установки R

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

Вы хотите скопировать ваше пакеты из более старой версии R в новую?

Жмём да. После чего вам будет задан вопрос «Сейчас ваши пакеты будут скопированы из старой версии R в новую, хотите ли вы сохранить их в старой версии языка R, если нажмёте нет все пакеты будут удалены из предыдущей версии R.».

Я рекомендую оставлять пакеты и нажимать в ответ «Да», т.к. не всегда все ваши пакеты успешно переходят из одной версии в другую.

Идём дальше, и отвечаем на следующий вопрос, «Хотите ли скопировать файл Rprofile.site из предыдущей версии R». Данный файл содержит некоторые переменные языка R, лучше ответить «Да».

И последний вопрос, хотите ли вы обновить все перенесённые из предыдущей версии R пакеты, лучше ответить «Да».

После обновления пакетов вам будет предложено перезапустить RGui для запуска новой версии R.

Вы хотите перезапустить RGui с наиболее актуальной версией R

Жмём «Да», и в приветственном сообщении видим информацию о том, что мы работаем в последней версии языка R.

На этом процесс обновления завершен. Но не смотря на то, что пакет installr перенесёт все установленные пакеты из предыдущей версии, всё же иногда возникают проблемы с переносом некоторых зависимых пакетов, поэтому всё таки я крайне рекомендую после обновления ядра R проверить работоспособность всех основных скриптов, хотя бы на уровне подключения библиотек.

Решение проблем которые могут возникнуть после обновления

Если у вас после обновление возникают проблемы с установкой новых пакетов, то стоит прочесть статью «Ошибка при установке R пакетов на Windows«.

Если вы сделали всё как в видео, но при этом пакеты небыли скопированы, просто найдите папку R/win-library, как правило, она располагается в папке документов по следующему пути — C:\Users\UserName\Documents\R\win-library\3.X, где вместо X предыдущая версия R, которая была у вас установлена, а вместо UserName ваше имя пользователя операционной системе. И переименуйте папку 3.X в 4.0.

После чего на всякий случай запустите R в режиме администратора и используйте команду update.packages(checkBuilt=TRUE, ask=FALSE) для пересборки пакетов.

Напоминаю, что обо всех новостях языка R, и многих его пакетов удобно следить подписавшись на мой телеграм канал R4marketing.

Update R using RStudio

For completeness, the answer is: you can’t do that from within RStudio. @agstudy has it right — you need to install the newer version of R, then restart RStudio and it will automagically use the new version, as @Brandon noted.

It would be great if there was an update.R() function, analogous to the install.packages() function or the update.packages(function).

So, in order to install R,

  1. go to http://www.r-project.org,
  2. click on ‘CRAN’,
  3. then choose the CRAN site that you like. I like Kansas: http://rweb.quant.ku.edu/cran/.
  4. click on ‘Download R for XXX’ [where XXX is your operating system]
  5. follow the installation procedure for your operating system
  6. restart RStudio
  7. rejoice

—wait — what about my beloved packages??—

ok, I use a Mac, so I can only provide accurate details for the Mac — perhaps someone else can provide the accurate paths for windows/linux; I believe the process will be the same.

To ensure that your packages work with your shiny new version of R, you need to:

move the packages from the old R installation into the new version; on Mac OSX, this means moving all folders from here:

[where you’ll replace «2.15» and «3.0» with whatever versions you’re upgrading from and to. And only copy whatever packages aren’t already in the destination directory. i.e. don’t overwrite your new ‘base’ package with your old one — if you did, don’t worry, we’ll fix it in the next step anyway. If those paths don’t work for you, try using installed.packages() to find the proper pathnames.]

now you can update your packages by typing update.packages() in your RStudio console, and answering ‘y’ to all of the prompts.

finally, to reassure yourself that you have done everything, type these two commands in the RStudio console to see what you have got:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *