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



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:

TEXT 📖 Display only
# 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:

R
# 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
💡 Tip: Get into the good habit of "adding comments to every line of code." Studies show that when you look back at your own code six months later, code without comments is virtually impossible to understand.



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
⚠️ Note: R is case-sensitive, which is one of the most common pitfalls. Name, name, and NAME are three completely different variables.

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

R
# Assignment
x <- 10
y <- 20

# View a Single Variable
x
# [1] 10

# View All Variables(Equivalent to Environment Pane)
ls()
# [1] "x" "y"
💡 Tip: In RStudio's "Environment/History" pane (top right), click on a variable to see its value—it's much more intuitive than 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
R
# 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
⚠️ Note: In actual development, <<- and -> are rarely used. As a beginner, you only need to use <-.

(3) The Importance of Spaces: <- vs < -

R
# Correct: Assignment
x <- 10

# Error: This is "less-than sign" Plus "negative 10" (Comparison x and -10)
x < -10
⚠️ Note: <- 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

R
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()
💡 Tip: In this tutorial, use 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

100%
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

R
# 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")

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
100%
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"]
💡 Tip: For all examples in this tutorial, it is strongly recommended that you create a new RStudio Project (such as 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:

R
# 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:

BASH
Rscript hello.R

Expected Output:

TEXT 📖 Display only
Hello, World!
💡 Tip: 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

R
# ============================================
# 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)
▶ Try it Yourself

Expected Output:

TEXT 📖 Display only
=== 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

Q What is the difference between x <- 10 and x < -10?
A Pay attention to the spaces! 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 <-.
Q Can I use Chinese characters in variable names?
A Technically, yes (R 4.x supports UTF-8 variable names), but it is strongly discouraged. Chinese variable names can lead to: ① garbled characters across platforms; ② no one being able to find your question on Stack Overflow; ③ confusion during team collaboration. Stick to English plus underscores.
Q What is the difference between print() and directly entering a variable name (e.g., just typing x)?
A They are completely equivalent in the console—the R interpreter automatically calls 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(...).
Q Can deleted variables be restored?
A No, 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.
Q How do I choose between paste() and cat()?
A 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


📝 Exercises

  1. 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). Use cat() 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.

  2. Basic Exercise: Create a new RStudio project named r-basics. Within the project, create a script named variables.R and define five variables of different types (numeric, character, logical, complex, and null NA). Use typeof() to check the type of each variable, and take a screenshot of the output for each of the five typeof() commands and save it.

  3. Advanced Problem: Write a script that: ① uses paste() to concatenate "Hello" and "World" into "Hello-World" (sep = "-"); ② uses cat() to print the result; ③ uses nchar() to check the length of the concatenated string. After running the script, take a screenshot and save the console output.

  4. Challenge: Write an R script that does the following: ① Use setwd() to change the working directory to tempdir() (the R temporary directory); ② Use getwd() to print the current working directory; ③ Use save.image() to save the workspace to my_workspace.RData; ④ Use rm(list = ls()) to clear all variables; ⑤ Use load("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.

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%

🙏 帮我们做得更好

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

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