SMTPS33 : Mathematical Statistics With R Programming : Introduction to R Programming

R Programming · Introduction & Basics

Introduction to R Programming

Features · reserved words · identifiers · constants · variables · operators · precedence · strings · basic data types
read-only

Syllabus · Features of R – Reserved words – Identifiers – Constants – Variables – Operators – Operator Precedence – Strings – Basic Data Types Chapter 1 & 2.1-2.2

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.
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. The table below summarizes the key features, but let's understand each one in simple terms.

Complete programming language: decision-making, loops, recursion, I/O
Effective data handling and storage
Operators for arrays, lists, vectors, matrices
Large package ecosystem (10,000+ on CRAN)
High-quality graphics, publication-ready, interactive (plotly, shiny)
Extensible: C, C++, Fortran, Python integration
Object-oriented: S3, S4, R6
Statistical techniques: linear/nonlinear modelling, time-series, clustering, tests
Installing R

Before you can write R programs, you need to install the R software on your computer. The installation process is straightforward, but the steps differ slightly depending on your operating system. R is free and runs on Windows, Mac, and Linux.

Windows – download .exe from CRAN, launch Rgui.exe. Installs both 32-bit and 64-bit.
Linuxsudo apt-get install r-base (Debian/Ubuntu) or yum install R (Red Hat/Fedora).
Running R Programs

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

Command Prompt (Interactive) – type R at terminal, then commands at > prompt.

> first_str <- ello="" world=""> first_str
[1] "Hello World!"

R Script File – save code in .R file and run with Rscript test.R.

# test.R
str <- code="" ello="" str="" world="">

GUI (RStudio or RGui) – open script, select lines, Ctrl+R to run.

Comments in R

Single-line comment: # comment – everything after # is ignored. R does not support multi-line comments like /* ... */ or triple quotes.

# This entire line is a comment
x <- 10="" 42="" a="" after="" assign="" code="" comment="" is="" statement="" sum="" this="" to="" valid="" x="" y="" z="">
Reserved Words

Reserved words (keywords) have special meaning in R. You cannot use them as variable names.

ifelserepeatwhilefunction
forinnextbreakTRUE
FALSENULLInfNaNNA
NA_integer_NA_real_NA_complex_NA_character_...

Important: R is case-sensitive. TRUE is reserved, but True is not (though strongly discouraged).

Identifiers

An identifier is the name you give to a variable, function, or object. Rules:

  • Can contain letters (a-z, A-Z), digits (0-9), period (.), underscore (_).
  • First character must be a letter or a period. If starting with period, second character 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) or underscores (a_variable_name).

Constants

Constants (literals) are fixed values. R has numeric, integer, complex, character, and logical constants.

3.14 numeric (default)
42L integer (L suffix)
3+4i complex
pi, letters, LETTERS, month.name built-in
Variables

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

Assignment operators: <- (most common), =, -> (rightward), <<- (global).

variable.1 = c(1, 2, 3)
variable.2 <- -="" 1="" c="" ose="" otus=""> variable.3   # FALSE becomes 0, TRUE becomes 1

Dynamic typing example: a variable can change type.

var_1 <- 10i="" 10l="" 20="" 90.86="" character="" code="" complex="" integer="" morning="" numeric="" ood="" var_1="">

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

Operators in R

Operators are symbols that tell R to perform specific mathematical, logical, or relational operations. R provides five main types.

Arithmetic Operators
OperatorDescription
+Adds two vectors
-Subtracts second vector from first
*Multiplies vectors
/Divides first vector by second
%%Remainder (modulus)
%/%Integer division (quotient)
^Exponentiation
a <- 20="" 2="" 30="" 3="" 40="" 4="" b="" c="" cat="" exponentiation=", (a ^ b))</code></pre>

  <div class=" remainder=", (a %% b))
cat(" section-title="" um=", (a + b))
cat("> Relational Operators
OperatorDescription
<Less than
>Greater than
<=Less than or equal to
>=Greater than or equal to
==Equal to
!=Not equal to
Logical Operators
OperatorDescription
!Logical NOT
&Element-wise AND
&&AND (first element only)
|Element-wise OR
||OR (first element only)

In R, any number greater than 1 is considered TRUE in logical operations; zero is FALSE.

Assignment Operators
OperatorDescription
<-, <<-Leftwards assignment (normal / global)
->, ->>Rightwards assignment
=Leftwards assignment (similar, but different precedence)
Miscellaneous Operators
OperatorDescription
:Sequence (e.g., 3:9 creates 3 4 5 6 7 8 9)
%in%Membership – checks if element belongs to a vector
%*%Matrix multiplication
Operator Precedence

When an expression contains multiple operators, R evaluates them in order of precedence. Higher precedence first.

OperatorDescriptionAssociativity
^ExponentRight to Left
-x, +xUnary minus/plusLeft to Right
%% %/%Modulus, integer divisionLeft to Right
* /Multiplication, divisionLeft to Right
+ -Addition, subtractionLeft to Right
< > <= >= == !=RelationalLeft to Right
!Logical NOTLeft to Right
& &&Logical ANDLeft to Right
| ||Logical ORLeft to Right
<- <<-Leftward assignmentRight to Left
=AssignmentRight to Left
# Examples
2 ^ 3 * 4      # (2^3)*4 = 32
2 + 3 * 4      # 2 + 12 = 14
(2 + 3) * 4    # 20
10 - 5 - 2     # (10-5)-2 = 3
2 ^ 3 ^ 2      # 2^(3^2) = 512
Strings

Strings are sequences of characters. You can use single or double quotes.

S <- code="" e="" ello="" he="" morning="" ood="" oodbye="" quote_str1="" quote_str2="" r="" replied="" said="" world="">

readline(prompt="Enter: ") reads user input from console.

Basic Data Types in R

R's fundamental data types include numeric, integer, complex, logical, and character.

numeric 10.5
decimal (default)
integer 42L
whole with L suffix
complex 3+4i
real + imaginary
logical TRUE / FALSE
boolean values
character "text"
strings
Data TypeDescriptionExample
numericDecimal numbers (default)x <- 10.5
integerWhole numbers (use L)x <- 10L
complexReal + imaginary partx <- 3 + 4i
logicalTRUE / FALSEx <- TRUE
characterText / stringx <- "Hello"
Type Checking & Conversion
FunctionPurpose
class(x)Returns data type of x
is.numeric(x)Checks if numeric
is.integer(x)Checks if integer
is.complex(x)Checks if complex
is.logical(x)Checks if logical
is.character(x)Checks if character
as.numeric(x)Converts to numeric
as.integer(x)Converts to integer
as.complex(x)Converts to complex
as.logical(x)Converts to logical
as.character(x)Converts to character

Quick Reference Card

<- assignment # comment print() / cat() class() / typeof() ls() list variables rm() remove start:end sequence %in% membership readline() user input

Post a Comment

0 Comments