0% found this document useful (0 votes)
12 views16 pages

Introduction to R Programming Basics

The document provides an introduction to computing with a focus on R programming, covering topics such as numerical calculations, data types, and operations in R. It details how to handle missing values, create and manipulate vectors, and access data from built-in and external sources. Additionally, it distinguishes between system-defined and user-defined objects in R, along with their functionalities.

Uploaded by

hybridmen01
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views16 pages

Introduction to R Programming Basics

The document provides an introduction to computing with a focus on R programming, covering topics such as numerical calculations, data types, and operations in R. It details how to handle missing values, create and manipulate vectors, and access data from built-in and external sources. Additionally, it distinguishes between system-defined and user-defined objects in R, along with their functionalities.

Uploaded by

hybridmen01
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT1

General Introduction to Computing


Computing involves the use of computer systems and software to perform
mathematical calculations, data processing, logical reasoning, and automation of
tasks. It forms the backbone of all digital analysis and data science workflows.

In the context of R programming, computing refers to using the R language to


perform:

- Numerical and logical computations

- Statistical analysis

- Data visualization

- Data manipulation and storage

- Automation of repetitive analysis through scripting

R is an interpreted, high-level, open-source programming language primarily used


for statistical computing and graphics.

Using R as a Calculator
R functions as a powerful calculator and supports various arithmetic operations:

Operation | Symbol | Example | Output |


Addition + 5+3 8
Subtraction - 7-2 5
Multiplication * 4*2 8
Division / 10 / 2 5
Exponentiation ^ 2^3 8
Modulus %% 10 %% 3 1
Integer Division %/% 10 %/% 3 3

These operations can be directly entered into the R console for instant results.
DATA TYPES IN R

Numbers in R
R supports different types of numeric data:

a. Integer

- Whole numbers with an 'L' suffix.

Example:

x <- 5L

class(x) # "integer"

b. Double/Numeric

- Default type for decimal and real numbers.

Example:

y <- 3.14

class(y) # "numeric"

c. Complex

- Used to represent numbers with imaginary components.

Example:

z <- 2 + 3i

class(z) # "complex"

Words in R (Character Data)


Character data refers to textual values and is enclosed in single or double quotes.

Example:

name <- "R Programming"


class(name) # Output: "character"

# A sentence

msg <- "Welcome to R"

print(msg) # Output: "Welcome to R"

Common operations:

- Concatenation: paste("Hello", "World") → "Hello World"

- Length: nchar("Hello") → 5

Operation Function Example Output


Join words paste() paste("Hi", "R") "Hi R"
Count letters nchar() nchar("Hello") 5
Upper/lower case toupper() toupper("r") "R"
Extract part substr() substr("Tanya", 1, 3) "Tan"
Replace text in the first place sub() sub("cat", "dog", "cat toy") "dog toy"
Compare words == "apple" == "banana" FALSE

Character data is essential for handling labels, categories, or textual input in


datasets.

Logical Values in R
Logical data types represent truth values:

- TRUE or FALSE (can also be written as T or F)

a. Comparison Operators

Comparison operators in R are used to compare values, returning a logical result


(TRUE or FALSE). They are commonly used in if conditions, loops, and subsetting
data.
Operator Meaning Example Output

== Equal to 5 == 5 TRUE

!= Not equal to 5 !=3 TRUE

> Greater than 7>2 TRUE

< Less than 2<5 TRUE

>= Greater or equal 5 >= 5 TRUE

<= Less or equal 3 <= 5 TRUE

b. Logical Operators

Logical operators are used to combine or evaluate logical expressions (TRUE or


FALSE values). They are primarily used in conditional statements, filtering data, and
Boolean logic operations.

| Operator | Description | Example | Output |

& | Element-wise AND | TRUE & FALSE | FALSE |


| | Element-wise OR | TRUE | FALSE | TRUE |
! | NOT (negation) | !TRUE | FALSE |

Example:

x <- 10

y <- 5

(x > y) & (x == 10) # TRUE

(x < y) | (x == y) # FALSE
Missing values
Missing values refer to data entries that are not recorded or are unknown. In R,
these are represented as:

• NA (Not Available) — represents a missing or undefined value.

• NaN (Not a Number) — indicates undefined mathematical operations such as


0/0.

Handling missing values is essential in data analysis, as unhandled missing entries


can lead to inaccurate computations or errors in statistical models.

1. Identifying Missing Values Using [Link]()

The [Link]() function is used to detect missing values. It returns a logical vector
indicating whether each element is NA.

Example:

x <- c(NA, 3, 4, NA, NA, NA)

[Link](x)

Output:

TRUE FALSE FALSE TRUE TRUE TRUE

This indicates which elements in the vector are missing.

2. Removing Missing Values from a Vector

Missing values can be removed using logical indexing.

Example:

x <- c(1, 2, NA, 3, NA, 4)

x[![Link](x)]

Output:
[1] 1 2 3 4

The ![Link](x) expression returns only those elements of x that are not missing.

3. Missing Value Filter Functions in Modeling

Many modeling functions in R have a parameter [Link] that controls how missing
values are treated during model fitting.

Common missing value filter functions:

• [Link]: Removes rows that contain any NA values.

• [Link]: Throws an error if any NA values are found.

• [Link]: Removes rows with NA values but retains their positions for
future reference.

• [Link]: Keeps NA values and proceeds without modification.

Example:

students <- [Link](

Name = c("Amit", "Priya", "Raj", "Sara", "Neha"),

Marks = c(85, NA, 76, 90, NA),

Hours = c(5, 6, NA, 8, 7)

students

• [Link](students)
• [Link](students)
• [Link](students)
• [Link](students)
4. Working with Missing Values in Data Frames

a. Creating Sample Data Frame

Example:

data <- [Link](

A = c(1, 2, NA, 4, 5),

B = c(NA, 2, 3, NA, 5),

C = c(1, 2, 3, NA, NA)

b. Finding Total Number of Missing Values

sum([Link](data))

Output:

This returns the total count of missing values in the data frame.

c. Column-wise Count of Missing Values

colSums([Link](data))

Output:

ABC

122

This shows how many missing values are present in each column.

5. Visualizing Missing Values

To visually inspect where missing values occur in a dataset, the visdat package
provides helpful tools.

Required package:

[Link]("visdat")

library(visdat)
vis_miss(data)

The vis_miss() function generates a visual representation of present and missing


values in the dataset.

6. Removing Missing Values from a Dataset

The [Link]() function removes all rows from a data frame that contain at least one
missing value.

Example:

data <- [Link](data)

print(data)

Output:

ABC

2222

Only rows with complete data are retained; others are removed.

Summary of Functions

Task Function

Check for missing values [Link]()

Remove missing values [Link]()

Count total missing values sum([Link]())

Count missing values per column colSums([Link]())

Visualize missing values vis_miss()

Handle NAs in models [Link]


Vectors
In R, a vector is the simplest and most fundamental data structure. It is a collection
of elements of the same type. Vectors are used to store numeric data, character
strings, logical values, and more.

R supports homogeneous vectors, which means all elements in a vector must be of


the same data type.

Types of Vectors in R

• Numeric: Used for decimal or floating-point numbers


Example: c(1.5, 2.3, 3.8)

• Integer: Whole numbers declared with L


Example: c(1L, 2L, 3L)

• Character: A sequence of strings or text


Example: c("red", "blue", "green")

• Logical: TRUE or FALSE values


Example: c(TRUE, FALSE, TRUE)

• Complex: Numbers with imaginary parts


Example: c(1+2i, 3+0i)

• Raw: Raw bytes (not commonly used)


Example: [Link](c(1, 2, 3))

Creating a Vector

Vectors are created using the c() function:

numbers <- c(10, 20, 30)

colors <- c("Red", "Green", "Blue")

logical_values <- c(TRUE, FALSE)


Attributes of a Vector

Every vector in R has several important attributes:

Length

The length attribute returns the total number of elements in a vector.


Function: length()

v <- c(10, 20, 30)

length(v) # Output: 3

Type

The type of a vector refers to the kind of data it holds.


Functions: typeof(), class()

typeof(v) # Output: "double"

class(v) # Output: "numeric"

Names

The names attribute allows assigning meaningful labels to the vector elements.
This improves readability and accessibility.

scores <- c(85, 90, 95)

names(scores) <- c("Math", "Physics", "Chemistry")

scores["Physics"] # Output: 90

To retrieve all names:

names(scores)

Accessing Vector Elements

Elements of a vector can be accessed using:

• Indexing by position (e.g., v[1])

• Indexing by name (if names are assigned)


marks <- c(Math=88, English=75, Science=93)

marks[2] # Access by position

marks["Science"] # Access by name

Vector Operations

Vectors support vectorized operations, allowing you to perform calculations


element-wise.

a <- c(1, 2, 3)

b <- c(10, 20, 30)

a + b # Output: 11 22 33

a * b # Output: 10 40 90

System-Defined and User-Defined Objects in R


Understanding Objects in R

An object in R is any entity that stores data — this includes variables, functions,
data frames, vectors, etc.

System-Defined Objects

System-defined objects are the built-in objects that come preloaded with the R
environment. These include constants, functions, datasets, and variables that are
already available without explicitly creating them. They are part of R’s base
packages or other loaded packages and are automatically accessible to the user.

These are built-in objects automatically available in R:

• Constants: Constants in R are pre-defined values that remain fixed during


program execution.
ex:

pi – Mathematical constant 3.141593


letters – Vector of lowercase alphabets
LETTERS – Uppercase alphabets

• Functions: Functions in R are pre-written blocks of code that perform


specific tasks or calculations. R provides a rich set of built-in functions to
handle mathematical, statistical, and data manipulation operations
ex: mean(), sum(), sqrt(), paste(), seq(), etc.

• Datasets: Datasets in R are preloaded collections of data provided with R’s


base installation or packages.
Available through the data() function (e.g., iris, mtcars)

Examples:

pi # Output: 3.141593

letters[1:4] # Output: "a" "b" "c" "d"

mean(c(5, 10) # Output: 7.5

User-Defined Objects
User-defined objects are objects created explicitly by the user during an R session or
in a script. These can be variables, functions, data frames, lists, or any other data
structures defined to store and manipulate data according to the user’s
requirements.

They include:

• Variables: Variables in R are user-defined names used to store data values in


memory for later use. They can hold numbers, text, vectors, data frames, or
other objects. Assignment is usually done using <- or =.

Ex: x <- 100


• Vectors: Vectors in R are one-dimensional collections of elements of the
same data type (numeric, character, or logical). They are created using the c()
function.

Ex: colors <- c("Red", "Blue")

• User-Defined Functions: User-defined functions are functions created by


the programmer to perform specific tasks that are not covered by built-in
functions. They are defined using the function() keyword and can accept
inputs and return outputs.

add <- function(a, b) {

return(a + b)

add(5, 3) # Output: 8

Accessing Data in R
Definition:

Accessing data in R refers to the process of loading datasets into the R environment
for analysis. This data can either be built-in (within R packages) or external
(from files like .csv or .txt).

1. Accessing Data from Within the System (data())


R provides several built-in datasets that are included in packages like datasets,
stats, etc. These can be used for practice, learning, and analysis.

Function Used:

data()

Purpose:

• Lists all available datasets.


• Loads specific datasets into memory.

Syntax to Load a Dataset:

data("dataset_name")

Examples:

data() # Lists all datasets

data("iris") # Loads the iris dataset

head(iris) # Displays first 6 rows

summary(iris) # Gives summary statistics

Common Built-in Datasets:

• iris

• mtcars

• airquality

• CO2

• ToothGrowth

2. Accessing Data from Outside the System


R allows importing data from external sources like CSV files, text files, etc. Two
commonly used functions are [Link]() and scan().

a. [Link]() Function

This function is used to read structured tabular data from external text or CSV
files into a data frame.

Syntax:

[Link](file, header = TRUE/FALSE, sep = "delimiter")

Parameters:
• file: Name or path of the file.

• header: If TRUE, the first row is taken as column names.

• sep: Specifies the separator (like ",", " ")

Example:

data <- [Link]("[Link]", header = TRUE, sep = ",")

Output:

The data is stored as a data frame, which can be accessed and analyzed using R
functions.

b. scan() Function

The scan() function is used to read simple input values such as numbers or
character strings from a file or the console into a vector or list.

Syntax:

scan(file, what)

Example:

Suppose [Link] contains:

10 20 30 40

Then:

x <- scan("[Link]")

Output:

10 20 30 40

This creates a numeric vector from the file.


Difference Between [Link]() and scan()

Basis [Link]() scan()


Input type Tabular data (rows and Simple data (vectors)
columns)
Output Data frame Vector or list
Structure Structured (like CSV or table) Less structured
required
Common use Reading datasets like .csv files Reading raw numeric or character
data

You might also like