R: R Basic Syntax
Last updated: 2026-08-26
In the previous lesson, we installed R and RStudio and ran our first line of code
cat("Hello"). In this lesson, we’ll thoroughly master R’s “four basic syntax elements”—comments, variables, assignments, and output. This will serve as the foundation for the next 28 lessons.
R’s syntax differs somewhat from that of other languages: comments use # instead of //, assignments typically use <- instead of =, and string concatenation uses paste() instead of +. Understanding these four differences is half the battle when writing R code.
1. What You'll Learn
- How to Write Single-Line and Multi-Line Comments in R
- Naming Conventions and Best Practices for Variables
- The Differences Between the 4 Assignment Operators (
<-=-><<-) - Differences between the
print()andcat()output functions - The Concept of a Working Directory and Using RStudio Projects
RscriptRunning R scripts from the command line
2. Comments: Adding "Comments" to Code
Comments are text intended for human readers; the R interpreter completely ignores them. However, comments are not merely "decorations"—they are a programmer’s most important communication tool.
(1) Why are comments important?
Imagine looking back at the code you wrote six months from now:
# Code without comments:
x <- df %>% filter(age > 18) %>% mutate(group = ifelse(score >= 60, "pass", "fail"))
# Code with Comments:
# Filter 18 Adults aged 18 and older,and by score 60 Classified as "Approved"/Failed both groups
x <- df %>% filter(age > 18) %>% mutate(group = ifelse(score >= 60, "pass", "fail"))
The latter is immediately understandable, while the former takes 5 minutes to figure out. That’s the value of comments.
(2) R Comment Syntax
R Only single-line comments (using #), no /* */ block comments:
| Syntax | Supported | Description |
|---|---|---|
# This is a comment |
✅ | Single-line comment—the only method supported by R |
/* Multi-line */ |
❌ | R is not supported; a syntax error will be reported |
// Single line |
❌ | R Not supported; will return object '//' not found |
(3) How do I handle multi-line comments?
R does not have native multi-line comments, but there are two workarounds:
# Plan 1: Use this on every line # (Recommendations, Standard Practice)
# Line 1 Comments
# Line 2 Comments
# Line 3 Comments
x <- 10
# Plan 2:RStudio Keyboard Shortcuts(Most Commonly Used)
# Select multiple lines of code → Ctrl+Shift+C (macOS: Cmd+Shift+C)
# RStudio Automatically add to each line #,Click again to remove the comment
3. Variables and Naming Conventions
Variables are "containers" used to store data. R is a dynamically typed language, so you don't need to declare types in advance; you can simply assign values to variables.
(1) Naming Conventions (Must be followed; otherwise, an error will occur)
| Rule | Incorrect Example | Correct Example | Reason |
|---|---|---|---|
| Must contain only letters, numbers, underscores, and periods | 2age <- 25 ❌ |
age2 <- 25 ✅ |
Cannot start with a number |
| Cannot contain spaces | my name ❌ |
my_name ✅ |
Spaces are syntactic separators in R |
| The R keyword cannot be used | if <- 1 ❌ |
is_if <- 1 ✅ |
if is a control flow keyword |
| Case Sensitivity | Name and name are two different variables |
name (consistent capitalization) |
R is case-sensitive |
Name, name, and NAME are three completely different variables.
(2) Naming Conventions (Recommended)
There are two mainstream naming conventions in the R community; choose one and stick with it:
| Style | Example | Use Cases |
|---|---|---|
| snake_case (underscores) | user_name, total_count |
tidyverse style (recommended) |
| dot.case | user.name, total.count |
Old-style base R |
This tutorial consistently uses snake_case (in line with the style of modern R packages such as dplyr and ggplot2).
(3) View Variables
# Assignment
x <- 10
y <- 20
# View a Single Variable
x
# [1] 10
# View All Variables(Equivalent to Environment Pane)
ls()
# [1] "x" "y"
ls().
4. Assignment Operator: <- vs =
R has two top-level assignment operators; they are almost equivalent in function, but <- is recommended.
(1) Comparison of the Two Writing Styles
| Dimension | <- |
= |
|---|---|---|
| Top-level assignment | ✅ | ✅ |
| Creating local variables within a function | ✅ | ❌ (They are passed to the outer scope) |
| Passing Arguments in Function Calls | ❌ (Creates a variable with the same name) | ✅ |
| Community Conventions | ✅ Officially Recommended by R | ❌ Prone to Confusion |
| Readability | ✅ "Assign the right side to the left side" is clearly implied | ⚠️ Confusion with the mathematical "equals" symbol |
# Writing Style 1:<- (Recommendations)
x <- 10
# Writing Style 2:= (Available but not recommended)
x = 10
(2) Reverse Assignment -> and Global Assignment <<-
R also has two "advanced" assignment operators:
| Symbol | Purpose | Recommendation Level |
|---|---|---|
x <- 10 |
Standard Assignment (Right-to-Left) | ✅ Highly Recommended |
10 -> x |
Reverse assignment (left-to-right) | ⚠️ For identification purposes only when reading legacy code |
x <<- 10 |
Global assignment (penetrates function scope) | ❌ Rarely used |
<<- and -> are rarely used. As a beginner, you only need to use <-.
(3) The Importance of Spaces: <- vs < -
# Correct: Assignment
x <- 10
# Error: This is "less-than sign" Plus "negative 10" (Comparison x and -10)
x < -10
<- must be surrounded by spaces; otherwise, it will be interpreted as a comparison operator. Missing even one space can make a world of difference.
5. Output Functions: print() vs. cat()
R has two commonly used output functions, which serve different purposes.
(1) A Table That Shows the Differences at a Glance
| Characteristics | print() |
cat() |
|---|---|---|
| String quotes | Display "Alice" |
Do not display Alice |
| Vector Index | Show [1] 1 2 3 |
Hide 1 2 3 |
| Multi-parameter concatenation | ❌ Requires paste() |
✅ Direct concatenation |
| Line Break | Automatic Line Break | Manual Line Break Required \n |
| Automatic invocation | ✅ When entering an object directly in the console | ❌ Must be explicitly invoked |
| Use Cases | Debugging, Monitoring | Generating Reports, Text |
(2) Live Demonstration
name <- "Alice"
age <- 25
# print() -- General Output (with [1] and quotation marks)
print(name)
# [1] "Alice"
# cat() —— Concatenated Output(Recommendations,More flexible)
cat("Name:", name, ",Age:", age, "\n")
# Name: Alice ,Age: 25
(3) Other Output Functions
| Function | Purpose | Use Cases |
|---|---|---|
message() |
Normal message (can be suppressed by suppressMessages()) |
Progress prompt for long scripts |
warning() |
Warning (does not interrupt the program) | Indicates a risk but continues execution |
stop() |
Error (program interruption) | Fatal error; must be handled by tryCatch() |
cat() to output text messages and use print() to debug and view variable values.
6. Working Directory
When R starts up, it enters a working directory by default, and all file reading and writing takes place there.
(1) The Importance of the Working Directory
graph LR
A["R Process"] --> B["Working Directory<br/>(work dir)"]
B --> C["data/sales.csv<br/>(Relative Path = ./data/sales.csv)"]
B --> D["scripts/clean.R<br/>(Relative Path)"]
B --> E["output/report.html<br/>(Relative Path)"]
style A fill:#fff3cd
style B fill:#d4edda
If the working directory is incorrect, read_csv("data/sales.csv") will not be able to find the file.
(2) View and set the working directory
# View the current working directory
getwd()
# [1] "C:/Users/Alice/Documents"
# Set the working directory (Use / or \\, Do not use \)
setwd("C:/Users/Alice/Projects/my_r_project")
(3) Recommended Approach: RStudio Project
Doing this manually setwd() is prone to errors (problems may occur if the path contains Chinese characters or spaces). We recommend using an RStudio Project:
| Advantage | Description |
|---|---|
| Automatic Settings | Open the .Rproj file; the working directory is automatically set to the project root directory |
| Project Independence | Each project has its own set of .R history, environment, and packages, with no interference between them |
| Portable | Send the entire project folder to others without path conflicts |
| Git-Friendly | Best Practices for Integrating RStudio Projects with Git |
graph LR
A["File → New Project"] --> B["Select New Directory → New Project"]
B --> C["Enter the project name r-tutorial"]
C --> D["RStudio Create .Rproj Documents"]
D --> E["Open later .Rproj<br/>Automatic Working Directory Setup"]
r-tutorial) and place all .R scripts inside it.
7. Command-Line Execution: Rscript
If you want to run R scripts (for automation, scheduled tasks, or web backends) without opening RStudio, use Rscript.
(1) Create a script
Create a new file named hello.R in any location:
# hello.R
cat("Hello, World!\n")
(2) Running from the Command Line
Open the terminal (cmd / PowerShell on Windows, Terminal on macOS / Linux), and run the following command:
Rscript hello.R
Expected Output:
Hello, World!
Rscript is widely used in scenarios such as CI/CD, data pipelines, and Web APIs (R Plumber), and is a command that every R engineer must master.
8. Complete Example: Comprehensive Practice of Basic Syntax
Below is an example of a complete workflow that ties together all the concepts covered in this lesson.
▶ Example: Student Information Management Script
# ============================================
# Student Information Management Script
# File Name:student.R
# ============================================
# 1. Notes:Script Description
# Author:Alice
# Features:Define student information and output it
# Date:2026-07-02
# 2. Variable Assignment (Use <- No need =)
student_name <- "Alice"
student_age <- 20
student_score <- 95.5
is_passed <- TRUE
# 3. Use cat() Output (Recommendations, Flexible Assembly)
cat("=== Student Information ===\n")
cat("Name:", student_name, "\n")
cat("Age:", student_age, "\n")
cat("Score:", student_score, "\n")
cat("Did I pass?:", is_passed, "\n")
# 4. Use print() Debugging (with [1] Index)
print(student_name)
print(student_score)
# 5. Simple Calculations
final_score <- student_score * 0.6 + 100 * 0.4 # 60% End of Term + 40% Usually
cat("\nFinal Results(60% End of Term + 40% Usually):", round(final_score, 2), "\n")
# 6. Delete Variable(Use with caution)
rm(student_name, student_age, student_score, is_passed, final_score)
Expected Output:
=== Student Information ===
Name: Alice
Age: 20
Grades: 95.5
Did I pass?: TRUE
[1] "Alice"
[1] 95.5
Final Results(60% End of Term + 40% Usually): 97.3
(1) Procedure
| Step | Action | Description |
|---|---|---|
| 1 | Create RStudio Project r-basics |
File → New Project |
| 2 | Create student.R in the project |
Ctrl+Shift+N |
| 3 | Copy the code above | Paste the entire code |
| 4 | Select All → Ctrl+Enter |
Send to Console |
| 5 | View the output in the console | See 5 lines of "Student Information" |
❓ FAQ
x <- 10 and x < -10?x <- 10 is an assignment (assigning 10 to x), while x < -10 is a comparison (checking if x is less than -10). Missing a single space makes a world of difference. Get into the habit of adding spaces before and after <-.print() and directly entering a variable name (e.g., just typing x)?print() when it sees a bare variable. However, in script files (.R), x will not produce any output; you must explicitly use print(x) or cat(...).rm() is irreversible. To restore them, you must reassign their values. When using rm(list = ls()) to clear the environment, we recommend saving important variables to .RData (save.image()) first.paste() and cat()?paste() returns a string (which can be processed further), while cat() prints directly to the console (with no return value). Use paste() to concatenate into a new variable, and cat() for direct output.📖 Summary
- In R, use
#to write single-line comments (there is no/* */syntax for block comments); use the RStudio shortcutCtrl+Shift+Cto comment out multiple lines at once - Variable naming conventions: alphanumeric characters, underscores, and periods; cannot start with a number; case-sensitive; the
snake_casestyle is recommended - The preferred assignment operator is
<-(R community convention);=is used when passing arguments to functions;<-must be surrounded by spaces (to avoid confusion with< -) - Output functions:
print()General (with[1]index),cat()Concatenation (recommended, flexible),message()Normal message,warning()Warning,stop()Error - To view the working directory settings, use
getwd()/setwd(); We strongly recommend using an RStudio project to avoid path issues. - Use
Rscript hello.Rto run R scripts from the command line; suitable for automation, CI/CD, and Web API scenarios
📝 Exercises
-
Basic Exercise: Create a new script in RStudio and define five variables to store a piece of text (
name), your age (age), your weight (weight, floating-point number), whether you are a student (is_student, boolean), and your city (city). Usecat()to concatenate them into the output: "I am [name], [age] years old, weigh [weight] kg, live in [city], and [is_student] am still in school." Take a screenshot after running the script and save it. -
Basic Exercise: Create a new RStudio project named
r-basics. Within the project, create a script namedvariables.Rand define five variables of different types (numeric, character, logical, complex, and nullNA). Usetypeof()to check the type of each variable, and take a screenshot of the output for each of the fivetypeof()commands and save it. -
Advanced Problem: Write a script that: ① uses
paste()to concatenate"Hello"and"World"into "Hello-World" (sep = "-"); ② usescat()to print the result; ③ usesnchar()to check the length of the concatenated string. After running the script, take a screenshot and save the console output. -
Challenge: Write an R script that does the following: ① Use
setwd()to change the working directory totempdir()(the R temporary directory); ② Usegetwd()to print the current working directory; ③ Usesave.image()to save the workspace tomy_workspace.RData; ④ Userm(list = ls())to clear all variables; ⑤ Useload("my_workspace.RData")to reload. Verify that all variables are still present after reloading. After running the script, take a screenshot and save the complete output for all 5 steps.