TANSCHE : SMPTS33 - Mathematical Statistics with R Programming - Unit 1

R Programming Unit 1 – Complete Notes (TANSCHE)

📊 STATISTICS WITH R PROGRAMMING

Madurai Kamaraj University · II B.Sc. Mathematics, III Semester · TANSCHE Syllabus

ARO Study Circle

Chapter 1 · Introduction to R Programming

Syllabus: Features of R – Reserved words – Identifiers – Constants – Variables – Operators – Operator Precedence – Strings – Basic Data Types

What is R?

R is an open-source programming language and environment designed specifically for statistical computing and graphics. It is widely used by statisticians, data scientists, and researchers. R was created by Ross Ihaka and Robert Gentleman at the University of Auckland, New Zealand. The name "R" comes from the first letter of their first names.

  • Initial version released in 1995, stable beta in 2000.
  • R inherits features from the S language.
  • Core written in C, Fortran, and R itself.
  • Freely available under GNU General Public License.
  • Works on Linux, Windows, and Mac.
  • Provides both command-line and graphical interfaces.

1.1 Features of R

R has become the world's most widely used statistics programming language because of its rich set of features. Unlike many other statistical tools, R is not just a point-and-click software — it is a full programming language. This means you can write scripts, create functions, and automate complex workflows.

Key Features Explained:

  • Complete programming language: R supports decision-making (if-else), loops (for, while), recursion, and input/output. You can write programs just like in C or Python.
  • Data handling: R can efficiently store and manipulate large datasets, which is essential for statistical analysis.
  • Operators for complex data: R provides special operators that work directly on arrays, lists, vectors, and matrices without needing explicit loops.
  • Large package ecosystem: Over 10,000 packages available on CRAN for everything from genetics to finance.
  • High‑quality graphics: Publication‑ready plots, plus interactive graphics with plotly or shiny.
  • Statistical techniques: Linear/nonlinear modelling, time‑series, clustering, classification, hypothesis testing, and more.
  • Extensible: Write code in C, C++, Fortran, or Python and call it from R.
  • Object‑oriented: Supports S3, S4, R6 for modular, reusable code.

1.2 Installing R

Before you can write R programs, you need to install the R software on your computer. R is free and runs on Windows, Mac, and Linux.

1.2.1 Windows Installation

  1. Download the Windows installer (e.g., R‑3.4‑win.exe) from CRAN.
  2. Double‑click the downloaded .exe and accept default settings.
  3. For 64‑bit Windows, both 32‑bit and 64‑bit versions are installed.
  4. Launch R via: C:\Program Files\R\R3.4.2\bin\i386\Rgui.exe
  5. Double‑click to open the R‑GUI console.

1.2.2 Linux Installation

# Red Hat / Fedora / CentOS $ yum install R # Debian / Ubuntu $ sudo apt-get install r-base

After installation, launch the interactive prompt by typing R in the terminal.

1.3 Running R Programs

There are three main ways to run R code: interactively, as a script file, or using a GUI.

1.3.1 Command Prompt (Interactive Mode)

> first_str <- "Hello World!" > first_str [1] "Hello World!"

<- is the assignment operator. The output [1] indicates a vector of length 1.

1.3.2 R Script File

Save code with .R extension and run with Rscript:

# test.R str <- "Hello World!" str
$ Rscript test.R
[1] "Hello World!"

1.3.3 Using GUI (RStudio or RGui)

  • Open R‑GUI or RStudio.
  • File → Open Script, select your .R file.
  • Select lines, right‑click → Run line or selection (or Ctrl+R).

1.4 Comments in R

Comments start with # and are ignored by R.

# This entire line is a comment x <- 42 # comment after code y <- 10 z <- x + y # sum
Note: R does not support multi‑line comments like /* ... */. Use # on each line.

1.5 Reserved Words

Reserved words (keywords) have special meaning and cannot be used as variable names.

Reserved Words in R
if else repeat while function for in next break TRUE FALSE NULL Inf NaN NA NA_integer_ NA_real_ NA_complex_ NA_character_
  • if, else, repeat, while, for, in, next, break, function – control flow and functions.
  • TRUE, FALSE – logical constants.
  • NULL – absence of value.
  • Inf – infinity (e.g., 1/0).
  • NaN – Not a Number (e.g., 0/0).
  • NA – Not Available (missing value).
Case‑sensitive: TRUE is reserved, but True is not (avoid using it).

1.6 Identifiers

Names for variables, functions, or objects. Rules:

  • Letters (a‑z, A‑Z), digits (0‑9), period (.), underscore (_) allowed.
  • First character must be a letter or a period; if starting with period, second cannot be a digit.
  • Cannot use reserved words.
✅ Valid:
total, Sum, .date.of.birth, Sum_of_two, Rank2
❌ Invalid:
tot@1, 2um, _prod, TRUE, .0wl

Best practice: use periods as separators (e.g., a.variable.name) — also acceptable: underscores or camelCase.

1.7 Constants

Constants (literals) are fixed values.

  • Numeric: 3.14, 42 (default double).
  • Integer: suffix L, e.g., 42L.
  • Complex: suffix i, e.g., 3+4i.
x <- 3.14; typeof(x) # "double" z <- 42L; typeof(z) # "integer" w <- 3+4i; typeof(w) # "complex"

Built‑in constants: pi, letters, LETTERS, month.name, month.abb.

1.8 Variables

A variable is a named storage location. R is dynamically typed — type is determined by the value assigned.

Assignment Operators

OperatorDescription
<-, =Leftward assignment (most common: <-)
->, ->>Rightward assignment (rare)
<<-, ->>Global assignment
variable.1 = c(1,2,3) # equal sign variable.2 <- c("Lotus","Rose") # leftward (preferred) c(FALSE,1) -> variable.3 # rightward
variable.1: 1 2 3
variable.2: Lotus Rose
variable.3: 0 1

Dynamic typing example:

var_1 <- 10L # integer var_1 <- 20 + 10i # complex var_1 <- 90.86 # numeric var_1 <- "Good Morning" # character

Use ls() to list variables, rm() to remove.

1.9 Operators in R

1.9.1 Arithmetic Operators

OperatorDescription
+Adds two vectors.
-Subtracts second vector from the first.
*Multiplies first vector with the second.
/Divides the first vector with the second.
%%Remainder (modulus) of first vector divided by second.
%/%Integer division (quotient only).
^Exponentiation.
a <- c(10, 20, 30, 40) b <- c(2, 2, 4, 3) cat("Sum =", (a + b), "\n") cat("Difference =", (a - b), "\n") cat("Product =", (a * b), "\n") cat("Quotient =", (a / b), "\n") cat("Remainder =", (a %% b), "\n") cat("Integer Division =", (a %/% b), "\n") cat("Exponentiation =", (a ^ b), "\n")
Sum = 12 22 34 43
Difference = 8 18 26 37
Product = 20 40 120 120
Quotient = 5 10 7.5 13.33333
Remainder = 0 0 2 1
Integer Division = 5 10 7 13
Exponentiation = 100 400 810000 64000

1.9.2 Relational Operators

OperatorDescription
<Checks if element of first vector is less than corresponding element of second.
>Checks if greater than.
<=Less than or equal to.
>=Greater than or equal to.
==Equal to.
!=Not equal to.
a <- c(10, 20, 30, 40) b <- c(25, 2, 30, 3) cat(a, "Less Than", b, (a < b), "\n") cat(a, "Greater Than", b, (a > b), "\n") cat(a, "Less Than or Equal To", b, (a <= b), "\n") cat(a, "Greater Than or Equal To", b, (a >= b), "\n") cat(a, "Equal To", b, (a == b), "\n") cat(a, "Not Equal To", b, (a != b), "\n")
10 20 30 40 Less Than 25 2 30 3 TRUE FALSE FALSE FALSE
10 20 30 40 Greater Than 25 2 30 3 FALSE TRUE FALSE TRUE
10 20 30 40 Less Than or Equal To 25 2 30 3 TRUE FALSE TRUE FALSE
10 20 30 40 Greater Than or Equal To 25 2 30 3 FALSE TRUE TRUE TRUE
10 20 30 40 Equal To 25 2 30 3 FALSE FALSE TRUE FALSE
10 20 30 40 Not Equal To 25 2 30 3 TRUE TRUE FALSE TRUE

1.9.3 Logical Operators

Important: In R, any number greater than 1 is considered TRUE in logical operations. Zero is FALSE.
OperatorDescription
!Logical NOT (element‑wise).
&Element‑wise logical AND.
&&Logical AND (first element only).
|Element‑wise logical OR.
||Logical OR (first element only).
a <- c(0, 20, 30, 56) b <- c(2, 2, 30, 0) cat(a, "Logical NOT", !a, "\n") cat(a, "Element-wise AND", b, (a & b), "\n") cat(a, "AND (&&) first element only", b, (a && b), "\n") cat(a, "Element-wise OR", b, (a | b), "\n") cat(a, "OR (||) first element only", b, (a || b), "\n")
0 20 30 56 Logical NOT TRUE FALSE FALSE FALSE
0 20 30 56 Element-wise AND 2 2 30 0 FALSE TRUE TRUE FALSE
0 20 30 56 AND (&&) first element only 2 2 30 0 FALSE
0 20 30 56 Element-wise OR 2 2 30 0 TRUE TRUE TRUE TRUE
0 20 30 56 OR (||) first element only 2 2 30 0 TRUE

1.9.4 Assignment Operators

OperatorDescription
<-, <<-Leftwards assignment
->, ->>Rightwards assignment
var.a = c(0,20,TRUE) var.b <- c(0,20,TRUE) var.c <<- c(0,20,TRUE) # global c(1,2,TRUE) -> v1 c(1,2,TRUE) ->> v2 # global rightward

1.9.5 Miscellaneous Operators

OperatorDescription
:Creates a sequence of numbers (e.g., 3:9 → 3 4 5 6 7 8 9)
%in%Checks if an element belongs to a vector (returns TRUE/FALSE)
%*%Matrix multiplication (covered later)
var1 <- 3:9 var1 # 3 4 5 6 7 8 9 a <- 2; b <- 3; var <- 3:10 a %in% var # FALSE b %in% var # TRUE

1.10 Operator Precedence

Operators with higher precedence are evaluated first. When equal precedence, associativity determines order.

OperatorDescriptionAssociativity
^ExponentRight to Left
-x, +xUnary minus, unary plusLeft to Right
%% %/%Modulus, Integer DivisionLeft to Right
* /Multiplication, DivisionLeft to Right
+ -Addition, SubtractionLeft to Right
< > <= >= == !=Relational OperatorsLeft to Right
!Logical NOTLeft to Right
& &&Logical ANDLeft to Right
| ||Logical ORLeft to Right
-> ->>Rightward assignmentLeft to Right
<- <<-Leftward assignmentRight to Left
=Leftward assignmentRight to Left
# Exponentiation has higher precedence than multiplication 2 ^ 3 * 4 # (2^3)*4 = 32 # Multiplication before addition 2 + 3 * 4 # 2 + 12 = 14 # Parentheses change order (2 + 3) * 4 # 20 # Relational operators have lower precedence than arithmetic 2 + 3 > 4 # (2+3) > 4 = TRUE # Left-to-right for subtraction 10 - 5 - 2 # (10-5)-2 = 3 # Right-to-left for exponentiation 2 ^ 3 ^ 2 # 2^(3^2) = 512 # Right-to-left for leftward assignment x <- y <- 5 # x <- (y <- 5)

1.11 Strings

Strings are sequences of characters. Use single or double quotes.

s1 <- "Hello" s2 <- 'World' quote <- "She said, 'Hello!'" # single inside double

Reading strings from user input

n <- readline(prompt = "Enter your department name: ") # input: Mathematics print(n) # "Mathematics"
Quick Reference Card
Assignment: <- (preferred) or =
Comments: # at start of line or after code
Print: print(x) or cat(x)
Check type: class(x) or typeof(x)
List variables: ls()
Remove variable: rm(x)
Sequence: start:end (e.g., 3:9)
Membership: value %in% vector
Read user input: readline(prompt = "...")

1.12 Basic Data Types

R has five basic data types: numeric, integer, complex, logical, character.

1.12.1 Numeric

Decimal numbers (default).

x <- 10.5 y <- 42 class(x) # "numeric" class(y) # "numeric" is.integer(y) # FALSE

1.12.2 Integer

Whole numbers with L suffix.

z <- 42L class(z) # "integer" as.integer(3.14) # 3 (truncates)
Important Behaviors:
• Arithmetic between integer and numeric yields numeric.
• Converting decimal to integer truncates (no rounding).
• Logical: TRUE → 1, FALSE → 0.

1.12.3 Complex

w <- 3 + 4i class(w) # "complex"

1.12.4 Logical

TRUE / FALSE. In numeric contexts, TRUE → 1, FALSE → 0.

x <- 1; y <- 2 z <- x > y # FALSE class(z) # "logical"

1.12.5 Character

Text values in quotes.

x <- "abc" y <- as.character(7.8) class(y) # "character"

📋 Summary Table: Basic Data Types

Data TypeDescriptionExample
NumericDecimal numbers (default type)x <- 10.5
IntegerWhole numbers (use L suffix)x <- 10L
ComplexNumbers with real and imaginary partsx <- 3 + 4i
LogicalBoolean values (TRUE/FALSE)x <- TRUE
CharacterText/string valuesx <- "Hello"

🔍 Type Checking and Conversion Functions

FunctionPurpose
class(x)Returns the data type of x
is.numeric(x)Checks if x is numeric
is.integer(x)Checks if x is integer
is.complex(x)Checks if x is complex
is.logical(x)Checks if x is logical
is.character(x)Checks if x is character
as.numeric(x)Converts x to numeric
as.integer(x)Converts x to integer
as.complex(x)Converts x to complex
as.logical(x)Converts x to logical
as.character(x)Converts x to character

📘 R Programming · Unit 1 · TANSCHE Syllabus

Prepared by ARO Study Circle

Post a Comment

0 Comments