Chapter 1 Setup

1.1 Loading packages

In R, packages are collections of functions and data sets developed by the community. They enhance the capability of R by adding new functions for data manipulation, visualization, etc.

Note: To install packages, you usually need administrator rights. The command install.packages("") installs a package from CRAN. Replace the empty quotes with the package name.

# Installing a package from CRAN
install.packages("tidyverse")

# Loading the package into the R session
library(tidyverse)

1.2 Setting working directory

The working directory is the folder where R reads and saves files. Changing the working directory will make your life easier by reducing the need to specify full paths for files.

Note: Replace path with the path to your desired working directory. The second command sets the working directory to where your R script is located.

# Getting the current working directory
getwd()

# Setting the working directory to a specific path
setwd("path/to/your/directory")

# Setting the working directory to the location of your active R script
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))

1.3 Troubleshooting

Running into issues is a natural part of coding. Below are some common issues and how to resolve them.

1.3.1 Incorrect or Outdated R Version

Having the wrong or outdated version of R can cause compatibility issues with packages or scripts.

Note: You can check your current R version and compare it to the latest version available on CRAN.

# Check your current R version
current_version <- R.version$major
cat("Current R version:", current_version, "\n")

# Check latest R version from CRAN
latest_version <- readLines(con = url("https://cran.r-project.org/src/base/R-4/")) %>%
  str_extract("\\d\\.\\d\\.\\d") %>% 
  max(., na.rm = TRUE)
cat("Latest R version:", latest_version, "\n")

# Check RStudio version
rstudio_version <- rstudioapi::versionInfo()$version
cat("Current RStudio version:", rstudio_version)

If your R version is outdated, consider updating it from CRAN. For RStudio, download the latest version from the official RStudio website.

# For Windows, you can use installr package
if (!require(installr)) install.packages("installr")
library(installr)
updateR()

1.3.2 Package installation issues

If you encounter issues while installing packages, it might be due to a lack of administrative rights or dependency issues.

Note: Run the following commands in R to install a package with dependencies.

# Attempt to install a package and its dependencies
install.packages("package_name", dependencies = TRUE)

If you’re still encountering issues, it may be helpful to consult community forums or the package documentation.

1.3.3 Loading specific functions from packages

Sometimes, even after successfully installing and loading a package, you may encounter errors that R cannot find the function you are trying to use. This may be due to function name conflicts between packages, or you may not want to load all functions from a package into your R session to keep it clean.

Note: To specify a function from a particular package without loading the entire package, use the :: operator.

# Using a specific function from a package without loading the entire package
result <- psych::describe(your_data)

By doing this, you are calling the describe function specifically from the psych package, even if other packages have a function with the same name. This can help in avoiding function conflicts and keeping your R session less cluttered.

1.3.4 Missing package information or functions

If you encounter errors regarding missing packages or functions, first ensure the package is installed and loaded. You can use the help() function to access documentation on packages and their functions.

help("tidyverse")

1.3.5 Other errors one frequently encounters

1.3.5.1 Error: Object Not Found

This error occurs when you try to access a variable or object that does not exist in your current R environment.

Note: To clear your environment, which might help in resolving this issue, you can use:

rm(list=ls())  # Clear environment

1.3.5.2 Error: Graphics Not Found

This error usually occurs when there’s an issue with your plotting device.

Note: To clear the graphics window, you can use:

if (!is.null(dev.list())) dev.off() # Clear graphics window

1.3.5.3 Error: Console

This error is generic and can occur for various reasons.

Note: To clear the console, use:

cat("\014") # Clear console

1.3.5.4 Error: Package Not Found

This error occurs when you try to load a package that is not installed.

Note: To install the missing package, use:

install.packages("package_name")

1.3.5.5 Error: Cannot Allocate Memory

This error occurs when R cannot allocate more memory for an object.

Note: To manually invoke garbage collection, you can use:

gc()  # Garbage collection

1.3.5.6 RStudio not responding

This is not an R error but an issue with the RStudio IDE itself.

Note: The best approach is to restart RStudio.

1.3.5.7 Failed to load a specific package

If a package fails to load, you may need to reinstall it.

Note: To detach and then reinstall the package, use:

detach("package:package_name", unload=TRUE)
install.packages("package_name")

1.3.5.8 Failed to install package due to dependencies

Some packages depend on other packages to function correctly.

Note: To install the package along with its dependencies, use:

install.packages("package_name", dependencies = TRUE)

1.3.5.9 Non-zero exit status

This error can occur when a function throws a warning that’s converted to an error.

Note: To suppress all warnings, you can use:

options(warn = -1)

1.3.5.10 Error: ‘x’ must be numeric

This error occurs when a function expecting a numeric argument gets a different type.

Note: To explicitly convert a column to numeric, use:

data_frame$column <- as.numeric(data_frame$column)

1.3.5.11 RStudio graphics device error

If your graphics device encounters an error, you may need to turn it off.

Note: To turn off the graphics device, use:

dev.off()

1.3.5.12 Reset RStudio dettings to default

If RStudio is not working as expected, you may need to reset its settings.

Note: Delete the RStudio desktop settings manually, usually located in the RStudio-Desktop directory within the user profile directory.

1.3.5.13 Error: Could Not Find Function

This error occurs when you try to use a function from a package that’s either not installed or not loaded.

Note: To load the package containing the function, use:

library(package_name)

1.3.5.14 Update a specific package

Sometimes an outdated package could cause issues.

Note: To update a package, use:

install.packages("package_name")

1.3.5.15 Check for missing values

To identify missing values in your data frame.

Note: To check for missing values, use:

sum(is.na(data_frame))

1.3.5.16 Error: Subscript Out of Bounds

This error occurs when you try to access an index that does not exist in the data structure.

Note: To check the length of a vector or dimensions of other data structures, use:

length(vector_name)  # Check vector length

1.3.5.17 Setting CRAN mirror

Sometimes you might encounter issues while installing packages from CRAN.

Note: To set the CRAN mirror, use:

options(repos = c(CRAN = "https://cran.rstudio.com/"))

1.3.5.18 Error: Argument Is of Length Zero

This error usually occurs when a function receives an empty object or null.

Note: Make sure variables are properly initialized and populated.

1.3.5.19 Cannot install packages

If you’re unable to install packages, it might be due to incorrect library paths.

Note: To check library paths, use:

.libPaths()  # Check library paths

1.3.5.20 Error: Package or Namespace Load Failed

This error occurs when there is an issue with the package or its namespace.

Note: To remove and reinstall the package, use:

remove.packages("package_name")
install.packages("package_name")

1.3.5.21 Failed to load ggplot2 or other tidyverse packages

If you can’t load ggplot2 or other tidyverse packages, reinstalling might help.

Note: To install the tidyverse package, use:

install.packages("tidyverse")

1.3.5.22 Warnings when loading a package

To suppress warnings when loading a package.

Note: To suppress warnings, use:

suppressWarnings(library(package_name))

1.3.5.23 Error: Could Not Find Function “%>%” or Other Pipe Operator

This error occurs when the pipe operator is not found.

Note: To load the magrittr package which contains the pipe operator, use:

library(magrittr)

1.3.5.24 Error: Could Not Find Function “%>%”

The %>% pipe operator is an essential tool in R for chaining commands and is included in the magrittr and dplyr packages, which are part of the tidyverse suite. If you encounter this error, it usually indicates that the package providing the operator has not been loaded correctly.

To resolve the issue, ensure that magrittr or the tidyverse is installed and then load it using the library() function.

# Install magrittr if it's not already installed
if (!require(magrittr)) install.packages("magrittr")

# Load magrittr to use the pipe operator
library(magrittr)

# Alternatively, load tidyverse, which includes magrittr
if (!require(tidyverse)) install.packages("tidyverse")
library(tidyverse)

After loading the appropriate package, the pipe operator %>% should be available for use in your R session.

1.3.5.25 Clear console

To clear the console screen.

Note: To clear the console, use:

cat("\014")  # Ctrl + L

1.3.5.26 Data frame column type issues

To check the data types of each column in a data frame.

Note: To check the structure of a data frame, use:

str(data_frame)  # Check structure

1.3.5.27 Error: Unexpected Symbol/Input/String Constant/Numeric Constant/SPECIAL in …

This error usually occurs when there’s a syntax error in your code.

Note: Check for misplaced symbols or quotes.

1.3.5.28 Functions not working after update

Sometimes, functions might not work as expected after you update them.

Note: To resolve this, restart your R session and reload packages.

1.3.5.29 Issues with rJava or other Java-Based packages

Java-related errors might require you to allocate more memory.

Note: To allocate more memory, use:

options(java.parameters = "-Xmx8000m")

1.3.5.30 RStudio crashes when plotting

This issue is often related to graphics drivers.

Note: Update graphics drivers and RStudio to the latest version.

1.3.5.31 Check the version of a specific package

To check the installed version of a package.

Note: To check the version of a package, use:

packageVersion("package_name")