Skip to main content
R Programming
CHAPTER 03 Beginner

R Syntax and Basics

Updated: May 18, 2026
5 min read

# CHAPTER 3

R Syntax and Basics

1. Chapter Introduction

Understanding R's syntax rules prevents the most common beginner errors. This chapter covers R's foundational syntax — how R reads code, comment conventions, output methods, and basic operations — culminating in a functional calculator application.

2. R Syntax Fundamentals

r
12345678910111213141516171819202122232425262728
# ─── COMMENTS ───────────────────────────────────────
# Single line comment starts with #
# R has no multi-line comment syntax — use # on each line

# ─── STATEMENTS ─────────────────────────────────────
x <- 5          # One statement per line (standard)
y <- 10; z <- 15  # Two statements with semicolon (avoid in scripts)

# ─── CASE SENSITIVITY ────────────────────────────────
Name <- "Alice"
name <- "Bob"   # Different from Name! R is case-sensitive
# Name and name are DIFFERENT variables

# ─── LINE CONTINUATION ───────────────────────────────
result <- 100 +
          200 +
          300   # R continues if line is syntactically incomplete

# ─── IDENTIFIERS (variable names) ────────────────────
my_variable <- 1       # snake_case (recommended)
myVariable  <- 2       # camelCase (OK)
my.variable <- 3       # dot.notation (R-specific, avoid new code)
.hidden_var  <- 4      # starts with dot (hidden from ls())

# INVALID names:
# 1name <- 5    → Cannot start with number
# my-var <- 5   → Hyphen not allowed
# if <- 5       → Cannot use reserved words

3. Output Methods

r
123456789101112131415161718192021222324252627282930
# print() — explicit printing (also works inside functions)
print("Hello, World!")
print(42)
print(c(1, 2, 3, 4, 5))

# cat() — concatenate and print (no [1] index prefix)
cat("Name:", "Alice", "\n")
cat("Sum:", 5 + 3, "\n")
cat("Pi:", pi, "\n")

# Difference:
x <- c(10, 20, 30)
print(x)   # [1] 10 20 30     (shows index [1])
cat(x)     # 10 20 30          (no index, no newline)

# sprintf() — formatted output (like C's printf)
name  <- "Alice"
score <- 95.5
cat(sprintf("%-10s scored %6.2f%%\n", name, score))
# Alice      scored  95.50%

# paste() — build strings
greeting <- paste("Hello", name, "!")     # "Hello Alice !"
greeting2 <- paste0("Hello", name, "!")  # "HelloAlice!" (no spaces)
cat(greeting, "\n")
cat(greeting2, "\n")

# Format numbers
cat(format(1234567.89, big.mark=",", nsmall=2), "\n")  # 1,234,567.89
cat(formatC(0.000123, format="e", digits=3), "\n")     # 1.230e-04

4. Basic Arithmetic and Operations

r
1234567891011121314151617181920
# Arithmetic
5 + 3    # 8
10 - 4   # 6
3 * 7    # 21
15 / 4   # 3.75
15 %/% 4 # 3  (integer division)
15 %% 4  # 3  (modulo/remainder)
2 ^ 10   # 1024 (exponentiation — also 2**10)
sqrt(16) # 4
abs(-7)  # 7

# Math functions
ceiling(3.2)   # 4  (round up)
floor(3.8)     # 3  (round down)
round(3.567, 2) # 3.57
trunc(3.9)     # 3  (toward zero)
log(100)       # 4.60 (natural log)
log10(1000)    # 3   (base-10 log)
log(8, base=2) # 3   (log base 2)
exp(1)         # 2.718 (e^1)

5. Mini Project: Basic Calculator Application

r
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
# ─── BASIC CALCULATOR APPLICATION ────────────────────

calculator <- function(a, b, operation) {
  result <- switch(operation,
    "+" = a + b,
    "-" = a - b,
    "*" = a * b,
    "/" = if (b != 0) a / b else stop("Division by zero!"),
    "^" = a ^ b,
    "%%" = a %% b,
    stop(paste("Unknown operation:", operation))
  )
  cat(sprintf("  %g %s %g = %g\n", a, operation, b, result))
  invisible(result)
}

# Scientific calculator additions
scientific_calc <- function(x, func) {
  result <- switch(func,
    "sqrt" = sqrt(x),
    "log"  = log(x),
    "exp"  = exp(x),
    "abs"  = abs(x),
    "sin"  = sin(x),
    "cos"  = cos(x),
    stop("Unknown function")
  )
  cat(sprintf("  %s(%g) = %g\n", func, x, result))
  invisible(result)
}

cat("=== CALCULATOR APPLICATION ===\n\n")
cat("Basic Operations:\n")
calculator(25, 7, "+")
calculator(100, 37, "-")
calculator(8, 9, "*")
calculator(144, 12, "/")
calculator(2, 10, "^")
calculator(17, 5, "%%")

cat("\nScientific Operations:\n")
scientific_calc(144, "sqrt")
scientific_calc(1, "exp")
scientific_calc(100, "log")
scientific_calc(-42, "abs")

cat("\nPractical Examples:\n")
# Circle calculations
r <- 7
cat(sprintf("  Circle (r=%g): Area=%.2f, Circumference=%.2f\n",
             r, pi * r^2, 2 * pi * r))

# Compound interest
P <- 10000; rate <- 0.05; years <- 10
amount <- P * (1 + rate)^years
cat(sprintf("  $%.0f at %.0f%% for %d years = $%.2f\n",
             P, rate*100, years, amount))

6. Common Mistakes

  • = in comparison vs assignment: In R, = is assignment inside function calls; == is equality comparison. Use <- for assignment in scripts.
  • Forgetting \n in cat(): print() adds a newline automatically. cat() does NOT — always add \n or use cat("text\n").

7. MCQs

Question 1

R is case-sensitive?

Question 2

cat() vs print() difference?

Question 3

Integer division in R uses?

Question 4

paste0("R", "Studio") returns?

Question 5

Modulo operator in R?

Question 6

sprintf("%.2f", 3.14159) returns?

Question 7

Valid R variable name?

Question 8

switch() in R is used for?

Question 9

log(100) in R computes?

Question 10

invisible(result) in a function?

8. Interview Questions

  • Q: What is the difference between cat() and print() in R?
  • Q: What does the %% operator do in R?

9. Summary

R syntax: one statement per line, # for comments, <- for assignment. Output: print() (structured with [1] index), cat() (plain text), sprintf() (formatted). Arithmetic: +, -, *, /, ^, %%, %/%. R is case-sensitive. Variable names: snake_case recommended. switch() for multi-branch logic.

10. Next Chapter Recommendation

In Chapter 4: Variables and Data Types in R, we master R's five fundamental data types — numeric, character, logical, integer, and complex — and type conversion.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·