Chapter 1 Installation & Environment Setup
What You’ll Learn:
- Package installation errors and how to fix them
- Understanding repository and connection issues
- Compilation errors on different operating systems
- Version compatibility problems
Key Errors Covered: 15+ installation-related errors
Difficulty: ⭐ Beginner to ⭐⭐ Intermediate
1.1 Introduction
Before you can make interesting errors in R, you need to install R and packages. Unfortunately, this is where many learners encounter their first frustrations. Installation errors are particularly annoying because they prevent you from even starting.
The good news: most installation errors follow predictable patterns and have standard solutions.
1.2 Error #1: Package Installation Failed
⭐ BEGINNER 📦 PACKAGE
1.2.1 The Error
🔴 ERROR
Warning in install.packages :
installation of package 'ggplot2' had non-zero exit status
1.2.2 What It Means
The installation process failed at some point. This is a generic error that can have many causes.
1.2.3 Common Causes and Solutions
1.2.3.3 Cause 3: Insufficient Permissions
Symptom: Permission denied errors on Windows/Mac/Linux
1.3 Error #2: Unable to Access Index for Repository
⭐ BEGINNER 📦 PACKAGE
1.3.1 The Error
🟡 WARNING
Warning: unable to access index for repository https://cran.rstudio.com/src/contrib
cannot open URL 'https://cran.rstudio.com/src/contrib/PACKAGES'
1.3.3 Solutions
✅ SOLUTIONS
1. Check CRAN status: - Visit https://cran.r-project.org/ in browser - If down, try different mirror
2. Change repository:
# Use RStudio's mirror
options(repos = c(CRAN = "https://cloud.r-project.org"))
# Or choose interactively
chooseCRANmirror()3. Force HTTP instead of HTTPS:
4. Check .Rprofile:
1.4 Error #3: Package Not Available for R Version
⭐⭐ INTERMEDIATE 📦 PACKAGE
1.4.1 The Error
🟡 WARNING
Warning message:
package 'newpackage' is not available for R version 4.0.0
1.4.2 What It Means
The package either: 1. Requires a newer R version 2. Is not on CRAN (wrong name or removed) 3. Has been archived
1.4.3 Solutions
✅ SOLUTIONS
1. Check R version:
2. Update R if needed:
- Download from https://cran.r-project.org/
- Or use installr package (Windows):
3. Check package name:
# Search for package
available.packages()[grep("package_name",
available.packages()[, "Package"]), ]4. Install from archive:
# If package was archived
packageurl <- "https://cran.r-project.org/src/contrib/Archive/package/package_1.0.tar.gz"
install.packages(packageurl, repos = NULL, type = "source")5. Install from GitHub:
💡 Key Insight: Package Lifecycle
Packages can be:
- On CRAN: Current and maintained
- Archived: Old version still available but removed from current CRAN
- On GitHub only: Development version or not submitted to CRAN
- Superseded: Replaced by another package (e.g., reshape → reshape2 → tidyr)
1.5 Error #4: Dependencies Not Available
⭐⭐ INTERMEDIATE 📦 PACKAGE
1.5.1 The Error
🔴 ERROR
ERROR: dependencies 'pkgA', 'pkgB' are not available for package 'complexpackage'
1.5.2 What It Means
The package needs other packages (dependencies) that aren’t available or can’t be installed.
1.5.3 Solutions
✅ SOLUTIONS
1. Install dependencies first:
# R usually does this automatically, but sometimes fails
install.packages("pkgA")
install.packages("pkgB")
install.packages("complexpackage")2. Force dependency installation:
3. Check for Bioconductor packages:
# Some dependencies are on Bioconductor, not CRAN
if (!requireNamespace("BiocManager", quietly = TRUE))
install.packages("BiocManager")
BiocManager::install("dependencyPackage")4. Manual dependency resolution:
1.6 Error #5: Lazy Loading Failed
⭐⭐ INTERMEDIATE 📦 PACKAGE
1.6.1 The Error
🔴 ERROR
Error: package or namespace load failed for 'ggplot2':
.onLoad failed in loadNamespace() for 'ggplot2', details:
call: NULL
error: lazy-load database 'path/to/ggplot2/R/ggplot2.rdb' is corrupt
1.6.3 Solutions
✅ SOLUTIONS
1. Reinstall the package:
2. Restart R session:
3. Check for partial installation:
# See package status
library(ggplot2)
packageVersion("ggplot2")
# Compare to CRAN version
available.packages()["ggplot2", "Version"]4. Install from source:
5. Clear package cache:
⚠️ Common Pitfall: Interrupted Installation
If you interrupt package installation (Ctrl+C or ESC): 1. The package may be partially installed 2. Loading it will fail with lazy-load errors 3. Always reinstall after interruption
Prevention: - Let installations complete - If it’s taking too long, check your internet connection first
1.7 Error #6: Package Built Under R Version
⭐ BEGINNER 📦 PACKAGE
1.7.2 What It Means
You’re using R 4.2.0, but the package was compiled for R 4.2.3. Usually this is fine, but can cause issues.
1.7.3 Should You Worry?
Usually NO - Minor version differences (4.2.0 vs 4.2.3) rarely cause problems.
Maybe YES - If you experience: - Strange errors from that package - Crashes - Unexpected behavior
1.7.4 Solutions
✅ SOLUTIONS
1. Ignore it (usually fine): Most of the time, this warning is harmless.
2. Update R:
# Check your version
R.version
# Update if significantly behind
# Windows: use installr
# Mac: download from CRAN
# Linux: use system package manager3. Reinstall package from source:
4. Suppress warning:
1.8 Error #7: Rtools Required But Not Installed
⭐⭐ INTERMEDIATE 📦 PACKAGE
Platform: Windows only
1.8.1 The Warning
🟡 WARNING
WARNING: Rtools is required to build R packages but is not currently installed.
Please download and install Rtools from https://cran.r-project.org/bin/windows/Rtools/
1.8.2 What It Means
You’re trying to install a package that needs compilation (C/C++/Fortran code), but Windows doesn’t have the necessary compilers.
1.8.3 Solutions
✅ SOLUTIONS
1. Install binary instead:
2. Install Rtools: 1. Download from https://cran.r-project.org/bin/windows/Rtools/ 2. Run installer (default options usually work) 3. Restart R/RStudio 4. Verify installation:
3. Configure PATH: Sometimes Rtools doesn’t add itself to PATH:
💡 Key Insight: Source vs Binary Packages
Binary packages: - Pre-compiled for your OS - Fast to install - Can’t modify source code
Source packages: - Raw R + C/C++ code - Requires compilation tools - Necessary for package development - Sometimes more up-to-date
On Windows: Use binaries unless you need source On Mac/Linux: Source compilation more common
1.9 Error #8: Library Not Found for -lX
⭐⭐⭐ ADVANCED 📦 PACKAGE
Platform: Mac/Linux
1.9.1 The Error
🔴 ERROR
ld: library not found for -lxml2
clang: error: linker command failed with exit code 1
1.9.2 What It Means
The package requires external libraries (system dependencies) that aren’t installed.
1.9.3 Solutions
✅ SOLUTIONS
Mac (using Homebrew):
# Install Homebrew if needed
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
# Install required library
brew install libxml2
# Then in R
install.packages("XML")Ubuntu/Debian:
Fedora/RedHat:
Common Dependencies:
🎯 Best Practice: Document System Requirements
If you’re sharing code that requires specific packages:
1.10 Error #9: Replacing Previous Import
⭐ BEGINNER 📦 PACKAGE
1.10.1 The Warning
🟡 WARNING
Attaching package: 'plyr'
The following objects are masked from 'package:dplyr':
arrange, count, desc, failwith, id, mutate, rename, summarise, summarize
1.10.2 What It Means
Both packages have functions with the same names. The later-loaded package’s functions will be used by default.
1.10.3 Should You Worry?
YES - This can cause confusing behavior if you expect dplyr’s mutate() but get plyr’s version.
1.11 Debugging Installation Issues
1.11.1 General Troubleshooting Steps
🎯 Systematic Approach
- Restart R
- Update R
- Update packages
- Check installation details
# Verbose output
install.packages("package", verbose = TRUE)
# Keep source for inspection
install.packages("package", INSTALL_opts = "--no-clean-on-error")- Check session info
sessionInfo()
#> R version 4.5.0 (2025-04-11)
#> Platform: x86_64-apple-darwin20
#> Running under: macOS Ventura 13.7.5
#>
#> Matrix products: default
#> BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
#> LAPACK: /Library/Frameworks/R.framework/Versions/4.5-x86_64/Resources/lib/libRlapack.dylib; LAPACK version 3.12.1
#>
#> locale:
#> [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
#>
#> time zone: Asia/Shanghai
#> tzcode source: internal
#>
#> attached base packages:
#> [1] stats graphics grDevices utils datasets methods base
#>
#> other attached packages:
#> [1] magick_2.9.0 rsvg_2.7.0 Rcpp_1.1.0
#> [4] R6_2.6.1 dbplyr_2.5.1 RSQLite_2.4.3
#> [7] DBI_1.2.3 writexl_1.5.4 readxl_1.4.5
#> [10] car_3.1-3 carData_3.0-5 lmtest_0.9-40
#> [13] zoo_1.8-14 ggrepel_0.9.6 patchwork_1.3.2
#> [16] rlang_1.1.6 assertthat_0.2.1 microbenchmark_1.5.0
#> [19] ggplot2_4.0.0 glue_1.8.0 stringr_1.5.2
#> [22] forcats_1.0.0 MASS_7.3-65 tibble_3.3.0
#> [25] purrr_1.1.0 dplyr_1.1.4 lubridate_1.9.4
#> [28] readr_2.1.5 tidyr_1.3.1
#>
#> loaded via a namespace (and not attached):
#> [1] tidyselect_1.2.1 viridisLite_0.4.2 farver_2.1.2 blob_1.2.4
#> [5] S7_0.2.0 fastmap_1.2.0 digest_0.6.37 timechange_0.3.0
#> [9] lifecycle_1.0.4 magrittr_2.0.4 compiler_4.5.0 sass_0.4.10
#> [13] tools_4.5.0 utf8_1.2.6 yaml_2.3.10 knitr_1.50
#> [17] labeling_0.4.3 bit_4.6.0 RColorBrewer_1.1-3 abind_1.4-8
#> [21] rsconnect_1.5.1 withr_3.0.2 grid_4.5.0 scales_1.4.0
#> [25] dichromat_2.0-0.1 cli_3.6.5 rmarkdown_2.30 crayon_1.5.3
#> [29] ragg_1.4.0 generics_0.1.4 rstudioapi_0.17.1 tzdb_0.5.0
#> [33] cachem_1.1.0 splines_4.5.0 parallel_4.5.0 cellranger_1.1.0
#> [37] vctrs_0.6.5 Matrix_1.7-3 jsonlite_2.0.0 bookdown_0.45
#> [41] hms_1.1.3 bit64_4.6.0-1 Formula_1.2-5 systemfonts_1.2.2
#> [45] jquerylib_0.1.4 hexbin_1.28.5 rematch_2.0.0 stringi_1.8.7
#> [49] gtable_0.3.6 pillar_1.11.1 htmltools_0.5.8.1 textshaping_1.0.0
#> [53] vroom_1.6.5 evaluate_1.0.5 lattice_0.22-6 memoise_2.0.1
#> [57] bslib_0.9.0 nlme_3.1-168 mgcv_1.9-1 xfun_0.53
#> [61] pkgconfig_2.0.3
# Shows R version, platform, loaded packages- Test in clean session
1.11.2 Getting Help
💡 When Asking for Help, Provide:
- Error message (complete, not summary)
- R version:
R.version.string - Platform:
Sys.info()["sysname"] - What you tried: Your code
- Session info:
sessionInfo()
Good question format:
I'm trying to install package X on Windows 11 with R 4.3.0.
Error message:
[paste complete error]
I tried:
- Updating R
- Different CRAN mirror
- Installing dependencies
sessionInfo() output:
[paste]
1.12 Summary
Key Takeaways:
- Most installation errors are environmental, not code-related
- Binary vs source matters on Windows
- System dependencies are common on Mac/Linux
- Package conflicts happen - use
package::function() - Reinstalling solves many issues
- Update regularly but cautiously
Quick Reference:
| Error | First Try |
|---|---|
| Installation failed | Restart R, try again |
| Repository access | Change CRAN mirror |
| Version mismatch | Update R |
| Dependencies missing | Install with dependencies = TRUE |
| Lazy-load corruption | Reinstall package |
| Rtools (Windows) | Install Rtools |
| Library not found (Mac/Linux) | Install system library |
| Package conflicts | Load order or use :: |
1.13 Exercises
📝 Exercise 1: Diagnosis Practice
What’s wrong with each scenario?
# Scenario 1
install.packages("dplyr")
# Warning: unable to access index for repository
# Scenario 2
library(ggplot2)
# Error: package 'ggplot2' was built before R 4.0.0
# Scenario 3
install.packages("devtools")
# ERROR: dependency 'usethis' is not availableAnswers at end of chapter
📝 Exercise 2: Prevention
Set up your R environment for smooth package installation:
- Configure a reliable CRAN mirror
- Set up a user library path
- Install essential build tools for your OS
- Create a package installation script
Try writing this setup code.
1.14 Exercise Answers
Click to see answers
Exercise 1:
Scenario 1: Cannot reach CRAN repository - Solution: Check internet, try different mirror
Scenario 2: R version too old - Solution: Update R to 4.0.0 or higher
Scenario 3: Missing dependency
- Solution: install.packages("devtools", dependencies = TRUE)
Exercise 2:
# Setup script
setup_r_environment <- function() {
# 1. Set CRAN mirror
options(repos = c(CRAN = "https://cloud.r-project.org"))
# 2. Set user library
user_lib <- "~/R/library"
if (!dir.exists(user_lib)) dir.create(user_lib, recursive = TRUE)
.libPaths(c(user_lib, .libPaths()))
# 3. Install essential packages
essentials <- c("devtools", "tidyverse", "rmarkdown")
new_packages <- essentials[!(essentials %in% installed.packages()[,"Package"])]
if(length(new_packages)) install.packages(new_packages)
# 4. Save to .Rprofile for future sessions
cat('options(repos = c(CRAN = "https://cloud.r-project.org"))\n',
file = "~/.Rprofile", append = TRUE)
message("R environment configured!")
}