Как установить rstudio на windows 10

Например, имя пользователя “Mashenka” подходит, а “Машенька” не подходит. Английское имя сильно облегчит жизнь в дальнейшем :) Проблема в том, что при взаимодействии Rstudio - R могут возникать проблемы, если в названии папки есть русские буквы, а у “Машеньки” путь к документам выглядит как “C:/Users/Машенька/”.
  • Пошаговая установка R для windows
  • Пошаговая установка R для macos
  • Пошаговая установка R для linux (на примере Ubuntu)
  1. Если Windows только-только поставлена, то, пожалуйста, создайте пользователя с логином английскими буквами и работайте из под него.

Например, имя пользователя “Mashenka” подходит, а “Машенька” не подходит. Английское имя сильно облегчит жизнь в дальнейшем :) Проблема в том, что при взаимодействии Rstudio — R могут возникать проблемы, если в названии папки есть русские буквы, а у “Машеньки” путь к документам выглядит как “C:/Users/Машенька/”.

Если компьютер давно используется с логином русскими буквами (“Машенька”), то оставляйте как есть, но:

При установке внимательно следите, что все программы ставятся в папки не содержащие русских букв. Мы рекомендуем поставить R в папку `C:/R`, а Rstudio в папку `C:/Rstudio`.
  1. На время установки отключите антивирус.

Нет, мы не хотим подсунуть слушателям хитрый троянский вирус :) Просто встречались с проблемами при установке, если антивирус включён.

  1. Установите классический R для windows.

Тем, кто уже знаком с R и не боится повозиться самостоятельно, мы советуем попробовать вместо классического R поставить MRO, Microsoft R Open. Это другой дистрибутив R, оптимизированный под работу с 64-битными процессорами. Всё полностью идентично, кроме двух нюансов: во-первых, MRO немного быстрее, во-вторых, MRO ставит все пакеты на единую дату, выбираемую пользователем, а классический R ставит самые свежие версии пакетов.

  1. Установите RStudio.

Rstudio — это всего лишь удобная красивая графическая оболочка к R. Суровые брутальные программисты могут вполне обойтись и без Rstudio :) Не спутайте Rstudio с R-studio, платной программой для восстановления данных.

  1. Настройте Rstudio.

Запустите RStudio. Зайдите в раздел Tools — Global options.

В разделе General:

* уберите галочку у Restore .Rdata into workspace in startup.
* выберите `Never` у Save workspace to .Rdata on exit

В разделе Sweave:

* "Weave .Rnw files using" выберите knitr.

В разделе Code — Diagnostics:

* выставьте все галочки.

  1. Установите свежую версию Rtools.

Это дополнительные программы, которые позволяют нам, в частности, из R создавать экселевские файлы.

  1. Шаг только для windows. Если имя пользователя windows набрано русскими буквами, а создавать нового никак не хочется!

7.1. Создайте папку для установки пакетов без русских букв и пробелов, например, C:/Rlib.

7.2. Создайте папку для временных файлов без русских букв и пробелов, например, C:/Temp.

7.3. Выполните в консоли Rstudio команду

system("setx R_LIBS C:/Rlib")
system("setx TEMP C:/Temp")
system("setx TMP C:/Temp")

Вместо C:/Rlib должно быть имя папки созданной для установки пакетов.

Вместо C:/Temp должно быть имя папки созданной для временных файлов.

7.4. Перезапустите Rstudio

7.5. Проверьте, что R знает, куда ему ставить пакеты. Для этого выполните в консоли Rstudio команду

.libPaths()

Она должна указать путь к папке C:/Rlib. После этого все пакеты будут ставиться в папку C:/Rlib.

  1. Установите все необходимые для курса пакеты R.

Скачайте файл install_all.R. Откройте его в RStudio (FileOpen file).

Если русские буквы видны как кракозябры, то после открытия файла выберите FileReopen with Encoding...UTF-8 и отметьте внизу галочку Set as default for source files.

Запустите скрипт, инсталлирующий пакеты, выбрав CodeSource with Echo. При этом требуется соединение с Интернетом.

При установке может встретиться вопрос: “Do you want to install from sources the packages which need compilation?”

Следует ответить “Нет”!

Причина: некоторые пакеты содержат код C++ и для установки из исходников (source) требуют наличия и корректной настройки компилятора C++ на компьютере. При ответе “Нет” будут скачаны уже заранее скомпилированые пакеты.

Бегущие красные надписи не означают ошибок, признаком ошибки является только явное сообщение Error.

  1. Не забудьте включить обратно антивирус :)

Пошаговая установка R для macos

  1. Установите классический R для macos.

Тем, кто уже хорошо знаком с R и не боится повозиться самостоятельно, мы советуем попробовать вместо классического R поставить MRO, Microsoft R Open. Это другой дистрибутив R, оптимизированный под работу с 64-битными процессорами. Всё полностью идентично, кроме двух нюансов: во-первых, MRO немного быстрее, во-вторых, MRO ставит все пакеты на единую дату, выбираемую пользователем, а классический R ставит самые свежие версии пакетов.

  1. Установите RStudio.

Rstudio — это всего лишь удобная красивая графическая оболочка к R. Суровые брутальные программисты могут вполне обойтись и без Rstudio :) Не спутайте Rstudio с R-studio, платной программой для восстановления данных.

  1. Запустите RStudio.

При первом запуске Rstudio может появится сообщение о необходимости установки Xcode command line tools (инструменты командной строки для разработчиков). Их нужно установить.

  1. Настройте Rstudio. Зайдите в раздел Tools — Global options.

В разделе General:

* уберите галочку у Restore .Rdata into workspace in startup.
* выберите `Never` у Save workspace to .Rdata on exit

В разделе Sweave:

* "Weave .Rnw files using" выберите knitr.

В разделе Code — Diagnostics:

* выставьте все галочки.

  1. Шаг только для Macos. Выполните в консоли Rstudio команду
system("defaults write org.R-project.R force.LANG en_US.UTF-8")

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

  1. Установите все необходимые для курса пакеты R.

Скачайте файл install_all.R. Откройте его в RStudio (FileOpen file). Запустите, выбрав CodeSource with Echo. При этом требуется соединение с Интернетом.

При установке может встретиться вопрос: “Do you want to install from sources the packages which need compilation?”

Следует ответить “Нет”!

Причина: некоторые пакеты содержат код C++ и для установки из исходников (source) требуют наличия и корректной настройки компилятора C++ на компьютере. При ответе “Нет” будут скачаны уже заранее скомпилированые пакеты.

Бегущие красные надписи не означают ошибок, признаком ошибки является только явное сообщение Error.

Пошаговая установка R для linux (на примере Ubuntu)

  1. Добавьте официальный репозиторий R:
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9
sudo add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/'
sudo apt update

Вместо bionic (для 18.04) должно быть кодовое название версии Ubuntu (disco для 19.04)

  1. Установите классический R:
sudo apt-get install r-base r-base-dev
  1. Установите RStudio.

Rstudio — это всего лишь удобная красивая графическая оболочка к R. Суровые брутальные программисты могут вполне обойтись и без Rstudio :) Не спутайте Rstudio с R-studio, платной программой для восстановления данных.

  1. Настройте Rstudio.

Запустите RStudio. Зайдите в раздел Tools — Global options.

В разделе General:

* уберите галочку у Restore .Rdata into workspace in startup.
* выберите `Never` у Save workspace to .Rdata on exit

В разделе Sweave:

* "Weave .Rnw files using" выберите knitr.

В разделе Code — Diagnostics:

* выставьте все галочки.

  1. Для пакетов R, скачивающих данные из Интернета, может потребоваться установка дополнительных библиотек linux
sudo apt-get install libcurl4-openssl-dev libxml2-dev libssl-dev
  1. Установите все необходимые для курса пакеты R.

Скачайте файл install_all.R. Откройте его в RStudio (FileOpen file). Запустите, выбрав CodeSource with Echo. При этом требуется соединение с Интернетом.

Бегущие красные надписи не означают ошибок, признаком ошибки является только явное сообщение Error.

Примечания:

  1. На ubuntu Rstudio узнает содержимое переменной PATH из файла etc/environ. Поэтому если в этом файле в переменной PATH нет пути к латеху, то Rstudio не увидит латех. Достаточно добавить путь к латеху в этом файле :)

Перевод инструкции с DataCamp

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

R — один из основных языков используемых сегодня в науке о данных. Поэтому любой, кому интересна эта сфера, может захотеть узнать, как начать пользоваться R вне зависимости от операционной системы, установленной на компьютере. Это руководство поможет установить R на Windows 10, Mac OS X и Ubuntu Linux.

Кроме того, в руководстве рассматриваются установка RStudio, мощной IDE (Integrated Development Environment, интегрированная среда разработки), упрощающей программирование на R, и установка пакетов для R, таких как dplyr или ggplot2.

С установкой R на Windows 10 нет никаких сложностей. Самый простой способ — установить его через CRAN (расшифровывается как The Comprehensive R Archive Network). Перейдите на страницу загрузок CRAN и проследуйте по ссылкам из анимации ниже:

Как только загрузка будет завершена, вы найдёте у себя файл под названием «R-3.6.3-win.exe» (либо похожим — в зависимости от номера версии R, которую вы скачаете). Ссылки в анимации выше помогут вам скачать самую актуальную версию. Всё, что осталось сделать для завершения установки R, это запустить загруженный exe-файл. По большей части, вам нужно просто соглашаться с опциями по умолчанию, так что просто нажимаете кнопку «Next» до завершения установки, как показано в следующей анимации. Обратите внимание, что на одном из экранов можно добавить иконки для вызова R через панель быстрого доступа и с рабочего стола (в анимации выбрана опция «Не добавлять».

Установка RStudio

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

Когда загрузка закончится, вы получите файл «RStudio-1.2.5033.exe», или с похожим названием — снова, в зависимости от версии. Запустите его, согласитесь с предлагаемыми по умолчанию настройками, нажимая кнопку «Next» и дождитесь окончания установки — как и в прошлый раз. Помните, что перед установкой RStudio необходимо установить R!

Установка пакетов в R

У вас уже установлены R и отличная IDE — можно начинать программировать. Однако, базовая версия R очень ограничена в возможностях, поэтому сообщество пользуется дополнительными пакетами, расширяющими функционал языка, такими как dplyr (расширяет возможности обработки данных) или ggplot2 (предоставляет улучшенные инструменты для визуализации). Есть два способа установки пакетов для R через RStudio. Первый — выполнить следующий код в консоли:

install.packages(c("dplyr","ggplot2"))

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

Установка R на Mac OS X

Процесс установки R на Mac OS почти не отличается от установки на Windows. Снова, самый простой способ — загрузить установщик со страницы загрузок CRAN:

Следующий шаг — запуск файла «R-3.6.2.pkg» (или более новой версии). Также, как и в Windows, можно оставить все опции по умолчанию.

Установка RStudio и пакетов R

В обоих случаях отличий от установки в Windows нет. Для загрузки RStudio перейдите на страницу загрузки и скачайте файл с расширением .dmg для Mac OS (как на картинке ниже). Оставляйте выборы по умолчанию.

Откройте RStudio. Установка пакетов проходит также, как в Windows. Можно ввести в консоль команду

install.packages(c("dplyr","ggplot2"))

или воспользоваться графическим интерфейсом, показанным в части «Установка пакетов в R» этого руководства.

Установка R в Ubuntu 19.04/18.04/16.04

Установка R в Ubuntu может быть несколько более сложной для тех, кто не привык работать в командной строке (консоли). Тем не менее, это практически также просто, как и в случаях с Windows или Mac OS. Прежде чем начать, убедитесь, что у вас есть права уровня root, позволяющие пользоваться sudo.

Как обычно, перед установкой R, давайте обновим список системных пактов, и обновим установленные пакеты, воспользовавшись двумя следующими командами:

sudo apt update
sudo apt -y upgrade

После этого, всё, что необходимо сделать для установки R — выполнить в консоли следующую команду:

sudo apt -y install r-base

Установка RStudio и пакетов R

Когда базовый R установлен, вы можете установить RStudio. Переходим на страницу загрузок, выбираем .deb файл для нашей версии Ubuntu, как на картинке ниже:

Когда вы скачали .deb файл, всё, что осталось сделать, это перейти в папку с загрузками, воспользовавшись командой

cd Downloads

и запустить оттуда процесс установки командой

sudo dpkg -i rstudio-1.2.5033-amd64.deb

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

sudo apt -f install

Когда установка закончится, иконка RStudio появится в списке приложений в Ubuntu, но вы также сможете запустить программу набрав rstudio в консоли.

В запущенной RStudio установка пакетов происходит ровно также, как в Windows или Mac OS. Либо введите

install.packages(c("dplyr","ggplot2"))

либо воспользуйтесь графическим интерфейсом, как показано в части «Установка пакетов в R» этого руководства.

Заключение

Я надеюсь, что это руководство поможет тем из вас, кто желает погрузиться в мир программирования на R вне зависимости от операционной системы, которой вы пользуетесь. Если вам интересно узнать о возможностях языка, воспользуйтесь курсом Введение в R от DataCamp, который познакомит вас с основами. Продолжайте учиться, нет предела совершенству!

Using Vagrant

This page is intended to help you configure your own machine for RStudio development. If you’d prefer an isolated development environment in a preconfigured virtual machine, you can use our Vagrant configuration script to create one (see RStudio Development for details).

Windows Bootstrapper

On a clean Windows-10 64-bit system, you can bootstrap RStudio development by following the instructions here. Otherwise, configure manually per the following instructions.

Installing R

On all platforms you need to install a version of R to target development against; you should install R before running any dependency installation scripts in RStudio.

RStudio itself is compatible with R version 3.0.1 or later, but version 3.1 or greater is recommended for development installations. The following are links to the installers for current, older, and development versions of R for all supported platforms.

Linux (Source)

A version of R exists in the package repository for most major versions of Linux, but it’s usually very outdated, so we recommend installing R binaries from CRAN instead.

  • Current version
  • Older versions
  • Development versions

Ubuntu Quickstart

If you’re building an Ubuntu dev box, here’s the tl;dr for getting R installed on Trusty (Ubuntu 14):

apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E084DAB9
echo 'deb http://cran.rstudio.com/bin/linux/ubuntu trusty/' >> /etc/apt/sources.list
apt-get update
apt-get install r-base

For Ubuntu 18:

apt install apt-transport-https software-properties-common
apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9
add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/'
apt update
apt install r-base

R for macOS

  • Current version
  • Older versions
  • Development versions

R for Windows

  • Current version
  • Older versions
  • Development version (patched)
  • Development version (future)

Make sure to install R to C:R, not C:Program FilesR as is the default, since RStudio’s build process needs to write additional symbol information into R’s installation directory, and will not have permission to write to Program Files.

Additional Dependencies (Linux)

gcc version

It is recommended that you build RStudio with GCC 4.8 or above. For Pro builds, this is required.

Also, on some platforms you must manually select and install an OpenJDK-8 or 11. Some of the dependency scripts mentioned below have been updated to install this for you, others have not. Please check the script to see if there is an openjdk reference in it.

Install Linux Dependencies

On Linux all dependencies for RStudio Server can be installed installed using the scripts in:

rstudio/
  dependencies/
    linux/

There is a separate script for systems with debian, yum, or zypper based package management. For example, to install dependencies for debian systems:

./install-dependencies-debian

Qt SDK for Linux (RStudio Spotted-Wakerobin or older)

If you are building against main, then the Qt SDK is no longer required. Starting with the Elsbeth-Geranium release (late 2022) we have moved RStudio Desktop off of Qt and onto Electron.

To build an older branch of RStudio Desktop, the Qt 5.12.10 SDK must be installed from https://qt.io.

5.12.10 won’t show up automatically when installing via the Qt online installer. To reveal it, click the «Archive» checkbox on the «Select Components» screen, then the Filter button. The list of available versions will expand to include all versions.

You should download and install this to the default location on your system (~/Qt).

The following components must be included to build RStudio Desktop on Linux:

  • Desktop gcc 64-bit
  • Qt WebEngine

Additional Dependencies (macOS)

C/C++ Tools

The C/C++ development tools required RStudio development can be obtained by installing the Command Line Tools for XCode. You can do this one of two ways. Either:

  1. Download and install XCode from the Mac AppStore: http://itunes.apple.com/us/app/xcode/id497799835?mt=12
  2. From a terminal, execute:

Or alternatively (for a smaller download size):

  1. Register as an Apple Developer (free) here: https://developer.apple.com/programs/register/
  2. Download the Command Line Tools for Xcode appropriate for the version of OS X you are running from here: https://developer.apple.com/downloads/

Other Dependencies

You should install the latest version of CMake from here:

  • CMake Download

Finally, you can install the remaining dependencies (including the Boost C++ libraries) using the script at:

You should switch to this directory and then execute:

./install-dependencies-osx

Note that this script requires Homebrew.

Also Note: As part of the install-dependencies-osx script, brew will install both ant and openjdk@11. If you run into GWT compile issues, make sure JAVA_HOME is set to use JDK 8 or 11, for example you can set it to 11 by running export JAVA_HOME=`/usr/libexec/java_home -v 11` (or adding it to your .zshrc).

Alternatively, on Mac or Linux (but not Windows), try using the shell script src/gwt/ant instead of running ant directly. This script will attempt to use the correct JDK (must be already installed) without you having to set JAVA_HOME yourself.

Another troubleshooting step when encountering GWT build failures (especially of the form «class file has wrong version» is to run ./ant clean then try building again.

Java Tools

In order to build the RStudio client GWT code, you need a JDK as well as the Ant build tool. You can install Java 8 or 11 from the following URL (note that newer JDKs are currently unsupported):

  • http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
  • https://www.oracle.com/java/technologies/downloads/#java11

Next, you can install Ant from one of the following URLs:

  • https://ant.apache.org/bindownload.cgi

Qt SDK for macOS (RStudio Spotted-Wakerobin or older)

If you are building against main, then the Qt SDK is no longer required. Starting with the Elsbeth-Geranium release (late 2022) we have moved RStudio Desktop off of Qt and onto Electron.

To build an older branch of RStudio Desktop, the Qt 5.12.10 SDK must be installed from https://qt.io.

5.12.10 won’t show up automatically when installing via the Qt online installer. To reveal it, click the «Archive» checkbox on the «Select Components» screen, then the Filter button. The list of available versions will expand to include all versions.

You should download and install this to the default location on your system (~/Qt).

The following components must be included to build RStudio Desktop on macOS:

  • Qt WebEngine
  • macOS

Additional Dependencies (Windows)

R

On Windows, prefer installing R into a location where your user account has write permissions (e.g. C:RR-x.y.z). This is necessary as RStudio will generate export libraries for the MinGW DLLs used by RStudio, so that the libraries can be consumed by MSVC. If you are not sure, reinstalling R under C:R will save some configuration time later on.

You will also want to be sure that the R executable is in your system or user %PATH%, such that typing R in cmd.exe starts the R interpreter. This is required by several RStudio dependency installation scripts.

Qt SDK for Windows (RStudio Spotted-Wakerobin or older)

If you are building against main, then the Qt SDK is no longer required. Starting with the Elsbeth-Geranium release (late 2022) we have moved RStudio Desktop off of Qt and onto Electron.

To build an older branch of RStudio Desktop, the Qt 5.12.10 SDK must be installed from https://qt.io.

5.12.10 won’t show up automatically when installing via the Qt online installer. To reveal it, click the «Archive» checkbox on the «Select Components» screen, then the Filter button. The list of available versions will expand to include all versions.

You should download and install this to the default location on your system (C:/Qt).

The following components must be included to build RStudio Desktop on Windows:

  • MSVC 2017 64-bit
  • Qt WebEngine

Microsoft Build Tools

RStudio uses Microsoft Build Tools 2017 for compilation on Windows. These can be downloaded here: https://www.visualstudio.com/vs/older-downloads/. Install these tools to the default location. If you’re using Qt Creator during development, it should automatically detect this as a ‘kit’ to use with RStudio.

CMake

You should install the latest version of CMake from here: CMake Download

NOTE: You should choose the «Add to system path» option during the installation.

Java Tools

In order to build the RStudio client GWT code, you need a JDK as well as the Ant build tool. You can install Java 8 from the following URL (note that Java 9 and 10 are currently unsupported):

  • http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

Next, you can install Ant from one of the following URLs:

  • https://ant.apache.org/bindownload.cgi
  • http://code.google.com/p/winant

Installer Tools

If you want to build RStudio installers for Windows, you should also install the Nullsoft Installer System (NSIS) from here: http://nsis.sourceforge.net

Other Dependencies

You can install the remaining dependencies (including the Boost C++ libraries) using the script at:

rstudio
   dependencies
      windows

You should switch to this directory and then execute:

Updating the System Path

Building RStudio requires that the CMake, and Qt be
accessible via the system path (note that CMake should already be accessible
via the CMake installer if the «Add to system path» option was chosen during
installation). For Qt, you should ensure that the following
additional directories are available on the path:

C:QtQt<version>ToolsQtCreatorbin

Finally, you should also ensure that your R installation’s bin directory is on the system path. For example:

C:Program FilesRR-3.0.1bini386

Building from Qt Creator

  • Open Qt Creator, Projects then Manage Kits.
  • Make sure the MSVC 2017 kit is the default.
  • If you didn’t install R at the recommended location (C:R), you will need to manually run the script that generates MSVC compatible export libraries for each of the R dlls. Follow the instructions below to do so:
    • Open a terminal as administrator
    • Navigate to the RStudio repo base folder
    • Run the following command: <Path to R installation>binx64Rscript.exe srccpptoolsdll2lib.R
      • The path to your R installation will change depending on what version of R you installed and what settings you chose at install time. (e.g. C:Program FilesRR-3.4.4)
    • Repeat this for x86 by running the following command: <Path to R installation>binx86Rscript.exe srccpptoolsdll2lib.R

Windows SDK

To make sure rstudio.bat runs correctly, install the latest version of Windows SDK from https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk, you might need to uninstall the installed version first, make sure at least the following options are selected:

Debugging tools for Windows
Windows app certification kit
Windows SDK Signing tools for desktop apps
Windows SDK for Desktop C++ x86 Apps
Windows SDK for Desktop C++ amd64 Apps

Miscellaneous

  • RStudio uses git during the build + install phases with cmake. On Windows, you can use the the Git installer provided here — after installing to the default location, you can put C:Program FilesGitcmd on the PATH (not C:Program FilesGitbin)

R programming language is a language and free software environment, available under GNU license, supported by R Foundation for Statistical Computing. The language is most widely known for its powerful statistical and data interpretation capabilities. 

To use R language, you need the R environment to be installed on your machine, and an IDE (Integrated development environment) to run the language (can also be run using CMD on Windows or Terminal on Linux). 

Why use R Studio?  

  • It is a powerful IDE, specifically used for the R language.
  • Provides literate programming tools, which basically allow the use of R scripts, outputs, text, and images into reports, Word documents, and even an HTML file.
  • The use of Shiny (open-source R package) allows us to create interactive content in reports and presentations.

Installing R Studio on Window

To Install R Studio on windows we will follow the following steps.

Step 1: First, you need to set up an R environment in your local machine. You can download the same from r-project.org. 

Step 2: After downloading R for the Windows platform, install it by double-clicking it.  

Installing R for Windows platform.

Step 3: Download R Studio from their official page. Note: It is free of cost (under AGPL licensing).  

Downloading R Studio for Windows.

Step 4: After downloading, you will get a file named “RStudio-1.x.xxxx.exe” in your Downloads folder. 

Step 5: Double-click the installer, and install the software. 

Step 6: Test the R Studio installation  

  • Search for RStudio in the Window search bar on Taskbar.

  • Start the application.
  • Insert the following code in the console.
Input  : print('Hello world!') 
Output : [1] "Hello world!"

R console on Windows.

Step 7: Your installation is successful.  

Installing R Studio on Ubuntu

Installing R Studio on Ubuntu has steps similar to Windows: 

Through Terminal 

Step 1: Open terminal (Ctrl+Alt+T) in Ubuntu.

Step 2: Update the package’s cache. 

sudo apt-get update

Step 3: Install R environment. 

sudo apt -y install r-base

Check for the version of R package using

R --version

Step 4: Check R installation by using the following command. 

user@Ubuntu:~$ R 

(Note that R version should be 3.6+ to be able to install all packages like tm, e1071, etc.). If there is issue with R version, see the end of the post. 

Step 5: Exit the terminal.

Through Ubuntu software Center 

Step 1: Open Ubuntu Software Center.

Step 2: Search for r-base.

Step 3: Click install. 

Install Rstudio on Ubuntu  

Step 1: Install gdebi package to install .deb packages easily.

sudo add-apt-repository universe
sudo apt-get install gdebi-core

Step 2: Go to R Studio downloads and select the latest *.deb package available under Ubuntu 18/Debian 10.

Step 3: Navigate to the Downloads folder in the local machine.

$ cd Downloads/
$ ls
 rstudio-1.2.5042-amd64.deb

Step 4: Install using gdebi package.

sudo gdebi rstudio-1.2.5042-amd64.deb

Step 5: Run the RStudio using Terminal

user@Ubuntu:~/Downloads/ $ rstudio 

Alternatively, use the menu to search for Rstudio.

Step 6: Test the R Studio using the basic “Hello world!” command and exit.

Input  : print('Hello world!') 
Output : [1] "Hello world!"

Alternatively, RStudio can be installed through Ubuntu Software as well, but using the above approach generally guarantees the latest version is installed. 

If there are issues with the R version getting downloaded or the previously installed version is older, check R version with 

R --version

Now, Run the following commands in Terminal (Ctrl + Alt + T)  

Add the key to secure APT from the CRAN package list:

sudo apt-key adv –keyserver keyserver.ubuntu.com –recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9

Add the latest CRAN repository to the repository list. (This is for Ubuntu 18.04 specifically):

sudo add-apt-repository ‘deb https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/’

Update the package cache:

sudo apt update

Install the r-base package:

sudo apt install r-base

R programming language is a language and free software environment, available under GNU license, supported by R Foundation for Statistical Computing. The language is most widely known for its powerful statistical and data interpretation capabilities. 

To use R language, you need the R environment to be installed on your machine, and an IDE (Integrated development environment) to run the language (can also be run using CMD on Windows or Terminal on Linux). 

Why use R Studio?  

  • It is a powerful IDE, specifically used for the R language.
  • Provides literate programming tools, which basically allow the use of R scripts, outputs, text, and images into reports, Word documents, and even an HTML file.
  • The use of Shiny (open-source R package) allows us to create interactive content in reports and presentations.

Installing R Studio on Window

To Install R Studio on windows we will follow the following steps.

Step 1: First, you need to set up an R environment in your local machine. You can download the same from r-project.org. 

Step 2: After downloading R for the Windows platform, install it by double-clicking it.  

Installing R for Windows platform.

Step 3: Download R Studio from their official page. Note: It is free of cost (under AGPL licensing).  

Downloading R Studio for Windows.

Step 4: After downloading, you will get a file named “RStudio-1.x.xxxx.exe” in your Downloads folder. 

Step 5: Double-click the installer, and install the software. 

Step 6: Test the R Studio installation  

  • Search for RStudio in the Window search bar on Taskbar.

  • Start the application.
  • Insert the following code in the console.
Input  : print('Hello world!') 
Output : [1] "Hello world!"

R console on Windows.

Step 7: Your installation is successful.  

Installing R Studio on Ubuntu

Installing R Studio on Ubuntu has steps similar to Windows: 

Through Terminal 

Step 1: Open terminal (Ctrl+Alt+T) in Ubuntu.

Step 2: Update the package’s cache. 

sudo apt-get update

Step 3: Install R environment. 

sudo apt -y install r-base

Check for the version of R package using

R --version

Step 4: Check R installation by using the following command. 

user@Ubuntu:~$ R 

(Note that R version should be 3.6+ to be able to install all packages like tm, e1071, etc.). If there is issue with R version, see the end of the post. 

Step 5: Exit the terminal.

Through Ubuntu software Center 

Step 1: Open Ubuntu Software Center.

Step 2: Search for r-base.

Step 3: Click install. 

Install Rstudio on Ubuntu  

Step 1: Install gdebi package to install .deb packages easily.

sudo add-apt-repository universe
sudo apt-get install gdebi-core

Step 2: Go to R Studio downloads and select the latest *.deb package available under Ubuntu 18/Debian 10.

Step 3: Navigate to the Downloads folder in the local machine.

$ cd Downloads/
$ ls
 rstudio-1.2.5042-amd64.deb

Step 4: Install using gdebi package.

sudo gdebi rstudio-1.2.5042-amd64.deb

Step 5: Run the RStudio using Terminal

user@Ubuntu:~/Downloads/ $ rstudio 

Alternatively, use the menu to search for Rstudio.

Step 6: Test the R Studio using the basic “Hello world!” command and exit.

Input  : print('Hello world!') 
Output : [1] "Hello world!"

Alternatively, RStudio can be installed through Ubuntu Software as well, but using the above approach generally guarantees the latest version is installed. 

If there are issues with the R version getting downloaded or the previously installed version is older, check R version with 

R --version

Now, Run the following commands in Terminal (Ctrl + Alt + T)  

Add the key to secure APT from the CRAN package list:

sudo apt-key adv –keyserver keyserver.ubuntu.com –recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9

Add the latest CRAN repository to the repository list. (This is for Ubuntu 18.04 specifically):

sudo add-apt-repository ‘deb https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/’

Update the package cache:

sudo apt update

Install the r-base package:

sudo apt install r-base

Install:

1. Run the downloaded RStudio8.exe file.

2. Select the language of the install process:
Language of the install process
Click image to enlarge

3. Run the Setup wizard.
Setup wizard
Click image to enlarge

4. Read the License Agreement and accept its conditions.
License Agreement
Click image to enlarge

5. Read the warning that you must not install the program on the disk where the lost files resided.
Warning
Click image to enlarge

6. If necessary, change the destination folder for the program.
Install folder
Click image to enlarge

7. If necessary, change the program group.
Install folder
Click image to enlarge

8. Wait while the program is being installed.
Install completed
Click image to enlarge

You may start the program as soon as the installation finishes.

Uninstall:

1. Go to the Control Panel, select Programs and Features, and double-click R-Studio:
Install program
Click image to enlarge

2. Select the language of the uninstall process.

3. Start the Uninstall wizard.
Uninstall wizard
Click image to enlarge

4. Start the uninstall process.
Uninstall process
Click image to enlarge

5. Wait while the uninstall process finishes.
Uninstall finished
Click image to enlarge

Register:

1. Upon receiving the email with the Registration key, open the attachment, then select and copy the key.

2. Go to the Help menu and select Register.

3. Enter your registration information and then paste the Registration key. Do not try to type it manually.
Registration dialog box
Click image to enlarge

4. Click the OK button.

R programming language is a free, open-source project for statistical computing. It compiles for UNIX-like platforms and several macOS and Windows versions. For running the latest version you will need Windows 7 or later or Mac OS X 10.6 and above. In this tutorial you will learn how to install R and RStudio.

  • 1 Installing R. The R project
  • 2 Install R on Windows
  • 3 Install R in mac OS
    • 3.1 Install R with Homebrew
  • 4 Install RStudio
  • 5 R basic commands
    • 5.1 A more detailed example
  • 6 Check where is R installed
  • 7 Check R version
  • 8 How to change the language in R GUI?

Installing R. The R project

The first step for becoming a Data Scientist or Data Analyst is having R installed on your computer. R can be freely downloaded in its official page. Note that installation requires up to 150 Mb of disk space available. The official web page of the R project is the following:

www.r-project.org/

In the previous link you can find interesting information about the R project, the R Foundation, the releases, documentation and other interesting links.

Install R on Windows

In order to install R on Windows, you can go through the following link and click on “Download R x.x.x for Windows” to start downloading the latest R version available.

https://cran.r-project.org/bin/windows/base/

Once downloaded, open it, select the preferred language and click Next to all dialogs.

Remember to select the path where you want to install R:

Note that you can uncheck the bit files that not correspond to your PC if desired.

You can also specify to customize some startup options:

When the installation finishes, you will be able to start using R base on Windows.

Install R in mac OS

The process of installing R in a mac is analogous to installing it in Windows. You can download the binary package (for Mac OS X 10.6 and above) from the following URL and then install it.

https://cran.r-project.org/bin/macosx/

If for some reason you are using Mac OS 8.6 to 9.2 (and Mac OS X 10.1) versions here you can find the old binary packages. For older Mac OS X systems and PowerPC Macs, you must use this repository to download R.

Install R with Homebrew

An alternative to install R in macOS is to use the Homebrew package manager. For that purpose you just need to type the following in the corresponding brew terminal:

$ brew install r

Install RStudio

RStudio is the most popular IDE for R, providing a clean and useful graphic interface for developing in R language. The main advantages of this IDE are the pane layout for getting help and displaying plots (even interactive), creating RMarkdown and Sweave documents, among others. You can download RStudio from the following link:

https://rstudio.com/products/rstudio/download/#download

Once downloaded, open the setup wizard and follow the simple steps.

R basic commands

After downloading R and RStudio open one and you will see the corresponding IDE (Integrated Development Environment). First, try to write direct commands in the commands window, where you can see the symbol > for start writing. Write the following and press Enter in the command line.

3 + 4
5 + 6 * 3

Those were your first R commands. Amazing!

You can also write in the script window and execute the code when you want. If this window doesn’t appear at first glance go to FileNew FileR Script or press Ctr + Shift + n or Cmd + Shift + n in Mac if you are using RStudio.

Once opened, copy and paste the code to the script, select it and press Ctr + r or Cmd + r in R base or Ctr + Enter or Cmd + Enter in RStudio (you can customize this). In the following block there are several examples you can try.

log(6)   # Log of 6
exp(8)   # Exponential of 8
sqrt(25) # Square root of 25
pi       # It recognizes the number pi

It should be noted that you can use # for comments that won’t be executed.

sin(3 * pi) # Sine function

You can also write several instructions within the same line, using a semicolon (;) as separator, although this practice is not recommended.

# Executing two commands in the same line
1 + 4; 2 * 3 - 8

If you want to store the values in variables you can use the = or <- sign. In R, it is more recommended using the arrow <-. If you want to print the stored variables in the console call the name or call the assignation between brackets.

a = 8 + 2
a # Prints the variable 'a'

b <- 1:15
b

a + b # Prints the result of the sum

A <- "car"
A

(A <- "car")  # Prints 'car' in the console

A more detailed example

Let’s see a more advanced example. We are going to simulate a normal random variable of size 200 with mean 105 and standard deviation of 2. Then, we make a summary and its corresponding histogram and boxplot.

# Seed for reproducibility
set.seed(1)

# Generating data
x <- rnorm(n = 200, mean = 105, sd = 2) 

# First elements of the data
head(x)

# Summary of the data
summary(x) 
107.1996 105.7260 105.0169 104.4441 105.6405 104.2416

 Min.   1st Qu.   Median  Mean   3rd Qu.    Max.
100.5   103.9     105.3   105.4   106.9    111.1
# Dividing the graphic window in two columns
par(mfcol = c(1, 2))

# Plotting a histogram
hist(x)

# Plotting a boxplot
boxplot(x, horizontal = TRUE) 

Check where is R installed

Sometimes it is useful to know the R installation path. The R.home function will output the path where you have R installed in your computer. Open R and type the following in the console if you want to check which is the installation path.

R.home()

Check R version

You can also check you have downloaded and installed the correct version typing:

R.Version()$version.string
"R version 4.0.0 (2020-04-24)"

In this case the output shows that we have installed the R version 4.0.0. You can have additional information about the version just typing R.Version().

How to change the language in R GUI?

By default, R will show the graphic user interface in the language of your operating system. To override this behavior and change the language permanently you can follow this steps:

  • Go to the R installation path. Recall to use the R.home() function if you don’t remember where it is.
  • Open the installation folder.
  • Open the etc folder.
  • Open the RConsole archive with a notepad.
  • Change the line language = for language = en if you want to set the language to English, or specify the language code you prefer.

August 5, 2020

In this tutorial we’ll learn how to begin programming with R using RStudio. We’ll install R, and RStudio RStudio, an extremely popular development environment for R. We’ll learn the key RStudio features in order to start programming in R on our own.

If you already know how to use RStudio and want to learn some tips, tricks, and shortcuts, check out this Dataquest blog post.

Table of Contents

  • 1. Install R
  • 2. Install RStudio
  • 3. First Look at RStudio
  • 4. The Console
  • 5. The Global Environment
  • 6. Install the tidyverse Packages
  • 7. Load the tidyverse Packages into Memory
  • 8. Identify Loaded Packages
  • 9. Get Help on a Package
  • 10. Get Help on a Function
  • 11. RStudio Projects
  • 12. Save Your “Real” Work. Delete the Rest.
  • 13. R Scripts
  • 14. Run Code
  • 15. Access Built-in Datasets
  • 16. Style
  • 17. Reproducible Reports with R Markdown
  • 18. Use RStudio Cloud
  • 19. Get Your Hands Dirty!
  • Additional Resources
  • Bonus: Cheatsheets

Getting Started with RStudio

RStudio is an open-source tool for programming in R. RStudio is a flexible tool that helps you create readable analyses, and keeps your code, images, comments, and plots together in one place. It’s worth knowing about the capabilities of RStudio for data analysis and programming in R.

RStudio Layout

Using RStudio for data analysis and programming in R provides many advantages. Here are a few examples of what RStudio provides:

  • An intuitive interface that lets us keep track of saved objects, scripts, and figures
  • A text editor with features like color-coded syntax that helps us write clean scripts
  • Auto complete features save time
  • Tools for creating documents containing a project’s code, notes, and visuals
  • Dedicated Project folders to keep everything in one place

RStudio can also be used to program in other languages including SQL, Python, and Bash, to name a few.

But before we can install RStudio, we’ll need to have a recent version of R installed on our computer.

1. Install R

R is available to download from the official R website. Look for this section of the web page:

Download R

The version of R to download depends on our operating system. Below, we include installation instructions for Mac OS X, Windows, and Linux (Ubuntu).

MAC OS X

  • Select the Download R for (Mac) OSX option.
  • Look for the most up-to-date version of R (new versions are released frequently and appear toward the top of the page) and click the .pkg file to download.
  • Open the .pkg file and follow the standard instructions for installing applications on MAC OS X.
  • Drag and drop the R application into the Applications folder.

Windows

  • Select the Download R for Windows option.
  • Select base, since this is our first installation of R on our computer.
  • Follow the standard instructions for installing programs for Windows. If we are asked to select Customize Startup or Accept Default Startup Options, choose the default options.

Linux/Ubuntu

  • Select the Download R for Linux option.
  • Select the Ubuntu option.
  • Alternatively, select the Linux package management system relevant to you if you are not using Ubuntu.

RStudio is compatible with many versions of R (R version 3.0.1 or newer as of July, 2020). Installing R separately from RStudio enables the user to select the version of R that fits their needs.

2. Install RStudio

Now that R is installed, we can install RStudio. Navigate to the RStudio downloads page.

When we reach the RStudio downloads page, let’s click the “Download” button of the RStudio Desktop Open Source License Free option:

Download R

Our operating system is usually detected automatically and so we can directly download the correct version for our computer by clicking the “Download RStudio” button. If we want to download RStudio for another operating system (other than the one we are running), navigate down to the “All installers” section of the page.

RStudio Desktop

3. First Look at RStudio

When we open RStudio for the first time, we’ll probably see a layout like this:

RStudio Desktop But the background color will be white, so don’t expect to see this blue-colored background the first time RStudio is launched. Check out this Dataquest blog to learn how to customize the appearance of RStudio.

When we open RStudio, R is launched as well. A common mistake by new users is to open R instead of RStudio. To open RStudio, search for RStudio on the desktop, and pin the RStudio icon to the preferred location (e.g. Desktop or toolbar).

4. The Console

Let’s start off by introducing some features of the Console. The Console is a tab in RStudio where we can run R code.

Notice that the window pane where the console is located contains three tabs: Console, Terminal and Jobs (this may vary depending on the version of RStudio in use). We’ll focus on the Console for now.

When we open RStudio, the console contains information about the version of R we’re working with. Scroll down, and try typing a few expressions like this one. Press the enter key to see the result.

1 + 2

As we can see, we can use the console to test code immediately. When we type an expression like 1 + 2, we’ll see the output below after hitting the enter key.

Console Example

We can store the output of this command as a variable. Here, we’ve named our variable result:

result <- 1 + 2

The <- is called the assignment operator. This operator assigns values to variables. The command above is translated into a sentence as:

> The result variable gets the value of one plus two.

One nice feature from RStudio is the keyboard shortcut for typing the assignment operator <-:

  • Mac OS X: Option + -
  • Windows/Linux: Alt + -

We highly recommend that you memorize this keyboard shortcut because it saves a lot of time in the long run!

When we type result into the console and hit enter, we see the stored value of 3:

> result <- 1 + 2
> result
[1] 3

When we create a variable in RStudio, it saves it as an object in the R global environment. We’ll discuss the environment and how to view objects stored in the environment in the next section.

5. The Global Environment

We can think of the global environment as our workspace. During a programming session in R, any variables we define, or data we import and save in a dataframe, are stored in our global environment. In RStudio, we can see the objects in our global environment in the Environment tab at the top right of the interface:

Global Environment

We’ll see any objects we created, such as result, under values in the Environment tab. Notice that the value, 3, stored in the variable is displayed.

Sometimes, having too many named objects in the global environment creates confusion. Maybe we’d like to remove all or some of the objects. To remove all objects, click the broom icon at the top of the window:

Broom Icon

To remove selected objects from the workspace, select the Grid view from the dropdown menu:

Grid

Here we can check the boxes of the objects we’d like to remove and use the broom icon to clear them from our Global Environment.

6. Install the tidyverse Packages

Much of the functionality in R comes from using packages. Packages are shareable collections of code, data, and documentation. Packages are essentially extensions, or add-ons, to the R program that we installed above.

One of the most popular collection of packages in R is known as the “tidyverse”. The tidyverse is a collection of R packages designed for working with data. The tidyverse packages share a common design philosophy, grammar, and data structures. Tidyverse packages “play well together”. The tidyverse enables you to spend less time cleaning data so that you can focus more on analyzing, visualizing, and modeling data.

Let’s learn how to install the tidyverse packages. The most common “core” tidyverse packages are:

  • readr, for data import.
  • ggplot2, for data visualization.
  • dplyr, for data manipulation.
  • tidyr, for data tidying.
  • purrr, for functional programming.
  • tibble, for tibbles, a modern re-imagining of dataframes.
  • stringr, for string manipulation.
  • forcats, for working with factors (categorical data).

To install packages in R we use the built-in install.packages() function. We could install the packages listed above one-by-one, but fortunately the creators of the tidyverse provide a way to install all these packages from a single command. Type the following command in the Console and hit the enter key.

install.packages("tidyverse")

The install.packages() command only needs to be used to download and install packages for the first time.

7. Load the tidyverse Packages into Memory

After a package is installed on a computer’s hard drive, the library() command is used to load a package into memory:

library(readr)
library(ggplot2)

Loading the package into memory with library() makes the functionality of a given package available for use in the current R session. It is common for R users to have hundreds of R packages installed on their hard drive, so it would be inefficient to load all packages at once. Instead, we specify the R packages needed for a particular project or task.

Fortunately, the core tidyverse packages can be loaded into memory with a single command. This is how the command and the output looks in the console:

library(tidyverse)## ── Attaching packages ───────────────────────────────────────────────── tidyverse 1.3.0 ──## ✓ ggplot2 3.3.2 ✓ purrr 0.3.4
## ✓ tibble 3.0.3 ✓ dplyr 1.0.0
## ✓ tidyr 1.1.0 ✓ stringr 1.4.0
## ✓ readr 1.3.1 ✓ forcats 0.5.0## ── Conflicts ──────────────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()

The Attaching packages section of the output specifies the packages and their versions loaded into memory. The Conflicts section specifies any function names included in the packages that we just loaded to memory that share the same name as a function already loaded into memory. Using the example above, now if we call the filter() function, R will use the code specified for this function from the dplyr package. These conflicts are generally not a problem, but it’s worth reading the output message to be sure.

8. Identify Loaded Packages

If we need to check which packages we loaded, we can refer to the Packages tab in the window at the bottom right of the console.

Packages

We can search for packages, and checking the box next to a package loads it (the code appears in the console).

Alternatively, entering this code into the console will display all packages currently loaded into memory:

(.packages())

Which returns:

[1] "forcats" "stringr" "dplyr" "purrr" "tidyr" "tibble" "tidyverse"
[8] "ggplot2" "readr" "stats" "graphics" "grDevices" "utils" "datasets" 
[15] "methods" "base"

Another useful function for returning the names of packages currently loaded into memory is search():

> search()
 [1] ".GlobalEnv" "package:forcats" "package:stringr" "package:dplyr" 
 [5] "package:purrr" "package:readr" "package:tidyr" "package:tibble" 
 [9] "package:ggplot2" "package:tidyverse" "tools:rstudio" "package:stats" 
[13] "package:graphics" "package:grDevices" "package:utils" "package:datasets" 
[17] "package:methods" "Autoloads" "package:base"

9. Get Help on a Package

We’ve learned how to install and load packages. But what if we’d like to learn more about a package that we’ve installed? That’s easy! Clicking the package name in the Packages tab takes us to the Help tab for the selected package. Here’s what we see if we click the tidyr package:

Package Help

Alternatively, we can type this command into the console and achieve the same result:

help(package = "tidyr")

The help page for a package provides quick access to documentation for each function included in a package. From the main help page for a package you can also access “vignettes” when they are available. Vignettes provide brief introductions, tutorials, or other reference information about a package, or how to use specific functions in a package.

vignette(package = "tidyr")

Which results in this list of available options:

Vignettes in package ‘tidyr’:nest nest (source, html)
pivot Pivoting (source, html)
programming Programming with tidyr (source, html)
rectangle rectangling (source, html)
tidy-data Tidy data (source, html)
in-packages Usage and migration (source, html)

From there, we can select a particular vignette to view:

vignette("pivot")

Now we see the Pivot vignette is displayed in the Help tab. This is one example of why RStudio is a powerful tool for programming in R. We can access function and package documentation and tutorials without leaving RStudio!

10. Get Help on a Function

As we learned in the last section, we can get help on a function by clicking the package name in Packages and then click on a function name to see the help file. Here we see the pivot_longer() function from the tidyr package is at the top of this list:

Tidyr Functions

And if we click on “pivot_longer” we get this:pivot_longer Help

We can achieve the same results in the Console with any of these function calls:

help("pivot_longer")
help(pivot_longer)
?pivot_longer

Note that the specific Help tab for the pivot_longer() function (or any function we’re interested in) may not be the default result if the package that contains the function is not loaded into memory yet. In general it’s best to ensure a specific package is loaded before seeking help on a function.

11. RStudio Projects

RStudio offers a powerful feature to keep you organized; Projects. It is important to stay organized when you work on multiple analyses. Projects from RStudio allow you to keep all of your important work in one place, including code scripts, plots, figures, results, and datasets.

Create a new project by navigating to the File tab in RStudio and select New Project.... Then specify if you would like to create the project in a new directory, or in an existing directory. Here we select “New Directory”:

Create Project

RStudio offers dedicated project types if you are working on an R package, or a Shiny Web Application. Here we select “New Project”, which creates an R project:

New Project

Next, we give our project a name. “Create project as a subdirectory of:” is showing where the folder will live on the computer. If we approve of the location select “Create Project”, if we do not, select “Browse” and choose the location on the computer where this project folder should live.

Name Project

Now in RStudio we see the name of the project is indicated in the upper-right corner of the screen. We also see the .Rproj file in the Files tab. Any files we add to, or generate-within, this project will appear in the Files tab.

Project Overview

RStudio Projects are useful when you need to share your work with colleagues. You can send your project file (ending in .Rproj) along with all supporting files, which will make it easier for your colleagues to recreate the working environment and reproduce the results.

12. Save Your “Real” Work. Delete the Rest.

This tip comes from our 23 RStudio Tips, Tricks, and Shortcuts blog post, but it’s so important that we are sharing it here as well!

Practice good housekeeping to avoid unforeseen challenges down the road. If you create an R object worth saving, capture the R code that generated the object in an R script file. Save the R script, but don’t save the environment, or workspace, where the object was created.

To prevent RStudio from saving your workspace, open Preferences > General and un-select the option to restore .RData into workspace at startup. Be sure to specify that you never want to save your workspace, like this:

Never Save Your Workspace

Now, each time you open RStudio, you will begin with an empty session. None of the code generated from your previous sessions will be remembered. The R script and datasets can be used to recreate the environment from scratch.

Other experts agree that not saving your workspace is best practice when using RStudio.

13. R Scripts

As we worked through this tutorial, we wrote code in the Console. As our projects become more complex, we write longer blocks of code. If we want to save our work, it is necessary to organize our code into a script. This allows us to keep track of our work on a project, write clean code with plenty of notes, reproduce our work, and share it with others.

In RStudio, we can write scripts in the text editor window at the top left of the interface:

R Script To create a new script, we can use the commands in the file menu:

R Script

We can also use the keyboard shortcut Ctrl + Shift + N. When we save a script, it has the file extension .R. As an example, we’ll create a new script that includes this code to generate a scatterplot:

library(ggplot2)
ggplot(data = mpg,
       aes(x = displ, y = hwy)) +
  geom_point()

To save our script we navigate to the File menu tab and select Save. Or we enter the following command:

  • Mac OS X: Cmd + S
  • Windows/Linux: Ctrl + S

14. Run Code

To run a single line of code we typed into our script, we can either click Run at the top right of the script, or use the following keyboard commands when our cursor is on the line we want to run:

  • Mac OS X: Cmd + Enter
  • Windows/Linux: Ctrl + Enter

In this case, we’ll need to highlight multiple lines of code to generate the scatterplot. To highlight and run all lines of code in a script enter:

  • Mac OS X: Cmd + A + Enter
  • Windows/Linux: Ctrl + A + Enter

Let’s check out the result when we run the lines of code specified above:

R Script

Side note: this scatterplot is generated using data from the mpg dataset that is included in the ggplot2 package. The dataset contains fuel economy data from 1999 to 2008, for 38 popular models of cars.

In this plot, the engine displacement (i.e. size) is depicted on the x-axis (horizontal axis). The y-axis (vertical axis) depicts the fuel efficiency in miles-per-gallon. In general, fuel economy decreases with the increase in engine size. This plot was generated with the tidyverse package ggplot2. This package is very popular for data visualization in R.

15. Access Built-in Datasets

Want to learn more about the mpg dataset from the ggplot2 package that we mentioned in the last example? Do this with the following command:

data(mpg, package = "ggplot2")

From there you can take a look at the first six rows of data with the head() function:

head(mpg)
## # A tibble: 6 x 11
##   manufacturer model displ  year   cyl trans      drv     cty   hwy fl    class 
##                          
## 1 audi         a4      1.8  1999     4 auto(l5)   f        18    29 p     compa…
## 2 audi         a4      1.8  1999     4 manual(m5) f        21    29 p     compa…
## 3 audi         a4      2    2008     4 manual(m6) f        20    31 p     compa…
## 4 audi         a4      2    2008     4 auto(av)   f        21    30 p     compa…
## 5 audi         a4      2.8  1999     6 auto(l5)   f        16    26 p     compa…
## 6 audi         a4      2.8  1999     6 manual(m5) f        18    26 p     compa…

Obtain summary statistics with the summary() function:

summary(mpg)
##  manufacturer          model               displ            year     
##  Length:234         Length:234         Min.   :1.600   Min.   :1999  
##  Class :character   Class :character   1st Qu.:2.400   1st Qu.:1999  
##  Mode  :character   Mode  :character   Median :3.300   Median :2004  
##                                        Mean   :3.472   Mean   :2004  
##                                        3rd Qu.:4.600   3rd Qu.:2008  
##                                        Max.   :7.000   Max.   :2008  
##       cyl           trans               drv                 cty       
##  Min.   :4.000   Length:234         Length:234         Min.   : 9.00  
##  1st Qu.:4.000   Class :character   Class :character   1st Qu.:14.00  
##  Median :6.000   Mode  :character   Mode  :character   Median :17.00  
##  Mean   :5.889                                         Mean   :16.86  
##  3rd Qu.:8.000                                         3rd Qu.:19.00  
##  Max.   :8.000                                         Max.   :35.00  
##       hwy             fl               class          
##  Min.   :12.00   Length:234         Length:234        
##  1st Qu.:18.00   Class :character   Class :character  
##  Median :24.00   Mode  :character   Mode  :character  
##  Mean   :23.44                                        
##  3rd Qu.:27.00                                        
##  Max.   :44.00

Or open the help page in the Help tab, like this:

help(mpg)

Finally, there are many datasets built-in to R that are ready to work with. Built-in datasets are handy for practicing new R skills without searching for data. View available datasets with this command:

data()

16. Style

When writing an R script, it’s good practice to specify packages to load at the top of the script:

library(ggplot2)

As we write R scripts, it’s also good practice add comments to explain our code (# like this). R ignores lines of code that begin with #. It’s common to share code with colleagues and collaborators. Ensuring they understand our methods will be very important. But more importantly, thorough notes are helpful to your future-self, so that you can understand your methods when you revisit the script in the future!

Here’s an example of what comments look like with our scatterplot code:

library(ggplot2)

# fuel economy data from 1999 to 2008, for 38 popular models of cars
# engine displacement (size) is depicted on the x-axis
# fuel efficiency is depicted on the y-axis
ggplot(data = mpg,
       aes(x = displ, y = hwy)) +
  geom_point()

17. Reproducible Reports with R Markdown

The comments used in the example above are fine for providing brief notes about our R script, but this format is not suitable for authoring reports where we need to summarize results and findings. We can author nicely formatted reports in RStudio using R Markdown files.

R Markdown is an open-source tool for producing reproducible reports in R. R Markdown enables us to keep all of our code, results, and writing, in one place. With R Markdown we have the option to export our work to numerous formats including PDF, Microsoft Word, a slideshow, or an html document for use in a website.

If you would like to learn R Markdown, check out these Dataquest blog posts:

  • Getting Started with R Markdown — Guide and Cheatsheet
  • R Markdown Tips, Tricks, and Shortcuts

18. Use RStudio Cloud

RStudio now offers a cloud-based version of RStudio Desktop called RStudio Cloud. RStudio Cloud allows you to code in RStudio without installing software, you only need a web browser. Almost everything we’ve learned in this tutorial applies to RStudio Cloud!

Work in RStudio Cloud is organized into projects similar to the desktop version. RStudio Cloud enables you to specify the version of R you wish to use for each project. This is great if you are revisiting an older project built around a previous version of R.

RStudio Cloud also makes it easy and secure to share projects with colleagues, and ensures that the working environment is fully reproducible every time the project is accessed.

The layout of RStudio Cloud is very similar to RStudio Desktop:

cloud

19. Get Your Hands Dirty!

The best way to learn RStudio is to apply what we’ve covered in this tutorial. Jump in on your own and familiarize yourself with RStudio! Create your own projects, save your work, and share your results. We can’t emphasize the importance of this enough.

Not sure where to start? Check out the additional resources listed below!

Additional Resources

If you enjoyed this tutorial, come learn with us at Dataquest! If you are new to R and RStudio, we recommend starting with the Dataquest Introduction to Data Analysis in R course. This is the first course in the Dataquest Data Analyst in R path.

For more advanced RStudio tips check out the Dataquest blog post 23 RStudio Tips, Tricks, and Shortcuts.

Learn how to load and clean data with tidyverse tools in this Dataquest blog post.

RStudio has published numerous in-depth how to articles about using RStudio. Find them here.

There is an official RStudio Blog.

If you would like to learn R Markdown, check out these Dataquest blog posts:

  • Getting Started with R Markdown — Guide and Cheatsheet
  • R Markdown Tips, Tricks, and Shortcuts

Learn R and the tidyverse with R for Data Science by Hadley Wickham. Solidify your knowledge by working through the exercises in RStudio and saving your work for future reference.

Bonus: Cheatsheets

RStudio has published numerous cheatsheets for working with R, including a detailed cheatsheet on using RStudio! Select cheatsheets can be accessed from within RStudio by selecting Help > Cheatsheets.

Ready to level up your R skills?

Our Data Analyst in R path covers all the skills you need to land a job, including:

  • Data visualization with ggplot2
  • Advanced data cleaning skills with tidyverse packages
  • Important SQL skills for R users
  • Fundamentals in statistics and probability
  • …and much more

There’s nothing to install, no prerequisites, and no schedule.

Понравилась статья? Поделить с друзьями:
  • Как установить rsat windows 10 20h2
  • Как установить rsat windows 10 2004
  • Как установить rsat powershell на windows 10
  • Как установить rosetta stone на windows 10
  • Как установить rosa linux рядом с windows