404 Not Found

404 Not Found


nginx

Introduction to R: What Is the R Statistical Programming Language?

R is the world’s most popular language for statistical computing and graphics—it makes data analysis and visualization simple and professional.

This tutorial is designed for beginners with no prior experience, starting with "What is R?" and progressing all the way to the point where you can complete a full data analysis project using R. R is the de facto standard in academic research, data science, and statistical modeling, and is used by over 2.5 million data scientists worldwide.

1. What You'll Learn



2. A Data Analyst’s True Story

(1) The Agony: Excel Can't Handle It Anymore

Alice is a market analyst who recently received an urgent assignment:

"Compile the @,000 rows of sales data from the past 12 months into a 6-page trend report covering different dimensions; the manager needs to see it tomorrow morning."

He opened Excel to get started, only to find that:

How did he manage to do it in the end? He switched to R.

(2) Solution using R

For the same task, Alice writes the following in R:

R
# Load the entire data analysis toolkit with a single line of code
library(tidyverse)

# Read in a single line of code @,000 rows ofData(5 Done in a second)
sales <- read_csv("sales_2024.csv")

# Draw with one line of code 6 Post a picture
sales |>
  group_by(region, month) |>
  summarise(total = sum(amount)) |>
  ggplot(aes(x = month, y = total, color = region)) +
  geom_line() +
  facet_wrap(~ product) +
  labs(title = "2024 Annual Sales Trends(By Region/Products)")

Total time: 5 minutes—5 seconds to read the data, 1 second to aggregate it, 3 seconds to create 6 charts, and the rest of the time spent polishing the titles.

That’s the beauty of R: performing the most complex data analysis with the least amount of code. Its design philosophy is “to let statisticians focus on thinking, rather than struggling with tools.”



3. What is R?

R is a programming language for statistical computing and graphics that was created in 1993 by Ross Ihaka and Robert Gentleman at the University of Auckland in New Zealand.

(1) The Three Main Roles of R

Category Description
The Statistician's Workbench Includes over 8,000 statistical functions covering all statistical methods, including descriptive statistics, hypothesis testing, regression, Bayesian analysis, time series analysis, and more
The Data Scientist's Brush ggplot2's charting syntax lets you create publication-quality graphics in a single line of code, surpassing the default style of Python's matplotlib
Standards for Reproducible Research R Markdown combines code, equations, figures, and text into a single document—the standard for journal submissions

(2) The Core Advantages of R



4. Differences Between R and Python

Many beginners ask, "Should I learn R or Python?" The answer is to learn both—but for different purposes.

(1) A Single Chart to Understand the Differences in Positioning

100%
graph TB
    subgraph Division of Labor Among Programming Languages
        A[R<br/>Statistical Analysis<br/>Academic Research<br/>Data Visualization] 
        B[Python<br/>Web Development<br/>Machine Learning<br/>Automation Engineering]
        C[SQL<br/>Database Query]
        D[JavaScript<br/>Front-End Interaction]
    end
    
    style A fill:#e1f5ff
    style B fill:#fff4e1
    style C fill:#f0e1ff
    style D fill:#e1ffe1

(2) Six-Dimensional Comparison Table

Dimension R Python
Design Goals For statisticians General-purpose programming language
Areas of Expertise Statistical Analysis, Data Visualization, Academic Research Web, Machine Learning, Automation, General Engineering
Data Science tidyverse chaining + ggplot2 pandas + matplotlib/sklearn
Learning Curve Functional Programming + Statistical Concepts Imperative Programming + Software Engineering
Package Ecosystem 20,000+ statistical packages on CRAN 400,000+ general-purpose packages on PyPI
Output Data Report (R Markdown) Application (Django/Flask)

(3) Brief Conclusion

💡 Tip: If you only want to learn one, choose R for data science, statistics, or research, and Python for engineering, web development, or AI. Data scientists typically know both, because using the right language for each task is the most efficient approach.



5. The Birth of R

(1) A Language with a Story

R wasn't designed out of thin air; it has a clear evolutionary path:

(2) Why has R lasted 30 years?

R isn't a "perfect" language (its syntax has its quirks, and the IDE is slow to start up), but the reason it has survived for 30 years is:

💡 Tip: Many languages "seem" perfect but are dead (Perl, Ruby, Haskell); R "seems" odd but is thriving more than ever. A language’s ultimate value lies in its ecosystem, not its syntax.



6. Install R (R 4.x main program)

R is open-source and free; you can download the installation package from the CRAN website.

(1) Installation Instructions for Each Platform

Platform Installation Method Notes
Windows Download R-4.x.x-win.exe, double-click and click "Next" through the installation wizard Select the version corresponding to your 64-bit system
macOS Apple Silicon Download R-4.x.x-arm64.pkg M1/M2/M3 chips
macOS Intel Download R-4.x.x-x86_64.pkg Older Macs
Linux (Ubuntu/Debian) Via the CRAN repository apt install See the command below
Linux (Fedora/CentOS) Via the EPEL repository dnf install See the official CRAN documentation

(2) Linux Installation Commands

BASH
# Ubuntu/Debian User:Execute the following commands one by one in the terminal
sudo apt update -qq
sudo apt install --no-install-recommends software-properties-common dirmngr
wget -qO- https://cloud.r-project.org/bin/linux/ubuntu/marutter_pubkey.asc | sudo tee -a /etc/apt/trusted.gpg.d/cran_ubuntu_key.asc
sudo add-apt-repository "deb https://cloud.r-project.org/bin/linux/ubuntu $(lsb_release -cs)-cran40/"
sudo apt install -y r-base

(3) Verify the installation

Once the installation is complete, open the system terminal and enter:

BASH
R --version

Expected Output:

TEXT
R version 4.4.1 (2024-06-14) -- "Race for Your Life"
Copyright (C) 2024 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu

If you see the R version number, it means the main program has been installed successfully.

⚠️ Note: Type R (in uppercase) in the terminal to enter the R interactive REPL; type q() to exit R. On Windows, you can also open R from the "Start Menu → R."



R comes with a basic graphical user interface, but 99% of R users use RStudio—an R-specific IDE developed by Posit, Inc., and the standard tool for R users worldwide.

(1) Download RStudio

Visit the Posit official website to download the free version of RStudio Desktop (available for Windows, macOS, and Linux; approximately 200 MB).

(2) RStudio Four-Pane View

When you open RStudio for the first time, you'll see four panes:

100%
graph TB
    A["Source Editor<br/>Source Editor<br/>Write R Scripts and Documentation"] 
    B["Console<br/>Console<br/>Execute Code,Display Results"]
    C["Environment/History<br/>Environment/History<br/>View Variables,Historical Commands"]
    D["Documents/Charts/Packages/Help<br/>Files/Plots/Packages/Help"]
    
    A -- "Ctrl+Enter<br/>Run the selected row" --> B
    B -- "Assignment Generation" --> C
    B -- "plot Drawing" --> D
    C -- "Click on the variable name to view" --> D
    
    style A fill:#fff3cd
    style B fill:#d4edda
    style C fill:#cce5ff
    style D fill:#f8d7da

(3) Four-Pane Menu

Pane Location Primary Purpose
Source Editor Top Left Write .R scripts and .Rmd documents; Ctrl+Enter send to the console
Console Bottom left Interactively execute R code; display output and error messages
Environment/History Top right Lists all current variables (data frames, functions, etc.); command history
Files/Plots/Packages/Help Bottom right Browse files, view plot results, install/load packages, look up function help
💡 Tip: If the interface is in English, you can use the Tools → Global Options → General → Appearance menu to switch the IDE theme (such as the Tomorrow Night Blue dark theme). However, it’s helpful to keep the menu in English so you can find answers when searching for error messages.



8. The First R Script

Now let’s write our first R script. The complete workflow is as follows:

▶ Example: Hello World + Simple Calculations

R
# ============================================
# My First R Screenplay
# File Name:hello.R
# ============================================

# 1. Comments are marked with # Introduction,Will not be executed
# 2. Used for variable assignment <-
name <- "World"

# 3. Use cat() Output (cat = concatenate, join)
cat("Hello,", name, "!\n")

# 4. R It's a calculator.(Enter the expression directly)
1 + 1
2 * 3
sqrt(144)  # Square Root = 12
log(100)   # Natural Logarithm

# 5. Performing Calculations Using Variables
pi_value <- 3.14159
radius <- 5
area <- pi_value * radius ^ 2
cat("The radius is", radius, "The area of the circle is approximately equal to", round(area, 2), "\n")
▶ Try it Yourself

Expected Output:

TEXT
Hello, World !
[1] 2
[1] 6
[1] 12
[1] 4.60517
The radius is 5 The area of the circle is approximately equal to 78.54

(1) Procedure

Step Action Description
1 In RStudio, press Ctrl+Shift+N Create a new R script
2 Enter the code above Copy and paste the entire code
3 Ctrl+S Save as hello.R Select a folder
4 Select all code Ctrl+A
5 Ctrl+Enter Send to console to run
6 View the output in the console See "Hello, World!"
💡 Tip: cat() is more flexible than print() and allows you to concatenate multiple parameters; \n is a line break; <- is R’s assignment operator (less-than sign + hyphen), which we’ll cover in more detail in the next lesson.



9. The R Package Ecosystem

R’s greatest strength is its package ecosystem—more than 20,000 open-source packages contributed by statisticians worldwide, covering virtually all statistical methods and data science scenarios.

(1) The Three Essentials of Package Management

R
# 1. Installation Package (Download from CRAN Mirror, Just do it once)
install.packages("dplyr")

# 2. Load Package(It must be loaded once for each new session.)
library(dplyr)

# 3. View Installed Packages
installed.packages()[, "Package"]

(2) tidyverse: The "Five-Piece Set" for Data Science in R

tidyverse is a collection of "tidy" packages led by Hadley Wickham (the author of ggplot2) and is the de facto standard for modern R data science:

Package Purpose Typical Functions
dplyr Data Processing filter() mutate() group_by() summarise()
ggplot2 Publication-quality graphics ggplot() geom_point() geom_bar()
readr Read/Write CSV/TSV read_csv() write_csv()
tidyr Data Reshaping pivot_longer() pivot_wider()
stringr String Processing str_detect() str_replace()
💡 Tip: Lesson 30 of this tutorial makes extensive use of the tidyverse. Install it once:

R
# One-time installation 8 A core package(dplyr/ggplot2/readr/tidyr/stringr/purrr/tibble/readxl)
install.packages("tidyverse")

❓ FAQ

Q Which should I install first, R or RStudio?
A You must install the R program first, then RStudio. RStudio is a "skin" for R and cannot run on its own. To use an analogy: install the engine first, then the cockpit.
Q Can I use R for machine learning?
A Yes, but R is more geared toward statistics and academia, while Python (PyTorch/TensorFlow) is by far the dominant language in the fields of AI and deep learning. If your goal is to transition into AI, I recommend learning Python; if your goal is data science or statistical modeling, R is more “authentic.”
Q Do I need to know Python before learning R?
A No. R is a standalone language, so you can start from scratch. However, if you learn both, you can choose the most appropriate tool for each task, which will maximize your efficiency. We recommend learning R first (for data science and statistics) and then learning Python when needed.
Q What should I do if R installation in China is slow or fails?
A In RStudio settings Tools → Global Options → Packages → CRAN mirror, switch to a Chinese mirror (such as Tsinghua https://mirrors.tuna.tsinghua.edu.cn/CRAN/); this will make the process 10 times faster. Linux users should also select a Chinese mirror when configuring the apt repository.

📖 Summary


📝 Exercises

  1. Basic Exercise: Visit the CRAN website, find the latest R installation package for your operating system, and note down the current version number. Install the R program and RStudio, then take a screenshot of RStudio’s four-pane interface and save it.

  2. Advanced Exercise: Create a new script in RStudio and write a "self-introduction" program: ① Define 3 variables (name name, age age, city city); ② Use cat() to construct a sentence and output "My name is [Name], I am [Age] years old, and I am from [City]"; ③ Use # to write 2–3 lines of comments explaining the code. After running the script, take a screenshot and save the console output.

  3. Challenge: Research one R package that interests you the most (recommended: ggplot2 / dplyr / shiny / rmarkdown / forecast), and write a paragraph (about 200 characters) describing its purpose, typical use cases, and a real-world example (which you can find on the RStudio website or CRAN Task Views). Save your research findings in a document.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏