0% found this document useful (0 votes)
2 views13 pages

Tutorial R

The document provides an overview of data types in R programming, detailing various R-objects such as vectors, lists, matrices, arrays, factors, and data frames. It explains how variables are assigned and managed in R, emphasizing that R is a dynamically typed language where variable types can change. Additionally, the document covers decision-making structures, loops, and functions in R, highlighting the syntax and usage of built-in and user-defined functions.

Uploaded by

Dr. Sunny Behal
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)
2 views13 pages

Tutorial R

The document provides an overview of data types in R programming, detailing various R-objects such as vectors, lists, matrices, arrays, factors, and data frames. It explains how variables are assigned and managed in R, emphasizing that R is a dynamically typed language where variable types can change. Additionally, the document covers decision-making structures, loops, and functions in R, highlighting the syntax and usage of built-in and user-defined functions.

Uploaded by

Dr. Sunny Behal
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

R Language Data Types

Generally, while doing programming in any programming language, you need to use various
variables to store various information. Variables are nothing but reserved memory locations to
store values. This means that, when you create a variable you reserve some space in memory.
You may like to store information of various data types like character, wide character, integer,
floating point, double floating point, Boolean etc. Based on the data type of a variable, the
operating system allocates memory and decides what can be stored in the reserved memory.
In contrast to other programming languages like C and java in R, the variables are not declared
as some data type. The variables are assigned with R-Objects and the data type of the R-object
becomes the data type of the variable. There are many types of R-objects. The frequently used
ones are −

• Vectors
• Lists
• Matrices
• Arrays
• Factors
• Data Frames
The simplest of these objects is the vector object and there are six data types of these atomic
vectors, also termed as six classes of vectors. The other R-Objects are built upon the atomic
vectors.

Data Type Example Verify

Logical TRUE, FALSE Live Demo

v <- TRUE
print(class(v))

it produces the following result −


[1] "logical"

Numeric 12.3, 5, 999 Live Demo


v <- 23.5
print(class(v))

it produces the following result −


[1] "numeric"

Integer 2L, 34L, 0L Live Demo


v <- 2L
print(class(v))

it produces the following result −


[1] "integer"
Complex 3 + 2i Live Demo
v <- 2+5i
print(class(v))

it produces the following result −


[1] "complex"

Character 'a' , '"good", "TRUE", '23.4' Live Demo


v <- "TRUE"
print(class(v))

it produces the following result −


[1] "character"

Raw "Hello" is stored as 48 65 6c 6c 6f Live Demo


v <- charToRaw("Hello")
print(class(v))

it produces the following result −


[1] "raw"

In R programming, the very basic data types are the R-objects called vectors which hold
elements of different classes as shown above. Please note in R the number of classes is not
confined to only the above six types. For example, we can use many atomic vectors and create
an array whose class will become array.

Vectors
When you want to create vector with more than one element, you should use c() function which
means to combine the elements into a vector.

Live Demo
# Create a vector.
apple <- c('red','green',"yellow")
print(apple)

# Get the class of the vector.


print(class(apple))

When we execute the above code, it produces the following result −


[1] "red" "green" "yellow"
[1] "character"

Lists
A list is an R-object which can contain many different types of elements inside it like vectors,
functions and even another list inside it.

Live Demo
# Create a list.
list1 <- list(c(2,5,3),21.3,sin)

# Print the list.


print(list1)

When we execute the above code, it produces the following result −


[[1]]
[1] 2 5 3

[[2]]
[1] 21.3

[[3]]
function (x) .Primitive("sin")

Matrices
A matrix is a two-dimensional rectangular data set. It can be created using a vector input to the
matrix function.

Live Demo
# Create a matrix.
M = matrix( c('a','a','b','c','b','a'), nrow = 2, ncol = 3, byrow = TRUE)
print(M)

When we execute the above code, it produces the following result −


[,1] [,2] [,3]
[1,] "a" "a" "b"
[2,] "c" "b" "a"

Arrays
While matrices are confined to two dimensions, arrays can be of any number of dimensions. The
array function takes a dim attribute which creates the required number of dimension. In the below
example we create an array with two elements which are 3x3 matrices each.

Live Demo
# Create an array.
a <- array(c('green','yellow'),dim = c(3,3,2))
print(a)

When we execute the above code, it produces the following result −


, , 1

[,1] [,2] [,3]


[1,] "green" "yellow" "green"
[2,] "yellow" "green" "yellow"
[3,] "green" "yellow" "green"

, , 2

[,1] [,2] [,3]


[1,] "yellow" "green" "yellow"
[2,] "green" "yellow" "green"
[3,] "yellow" "green" "yellow"

Factors
Factors are the r-objects which are created using a vector. It stores the vector along with the
distinct values of the elements in the vector as labels. The labels are always character
irrespective of whether it is numeric or character or Boolean etc. in the input vector. They are
useful in statistical modeling.
Factors are created using the factor() function. The nlevels functions gives the count of levels.

Live Demo
# Create a vector.
apple_colors <- c('green','green','yellow','red','red','red','green')

# Create a factor object.


factor_apple <- factor(apple_colors)

# Print the factor.


print(factor_apple)
print(nlevels(factor_apple))

When we execute the above code, it produces the following result −


[1] green green yellow red red red green
Levels: green red yellow
[1] 3

Data Frames
Data frames are tabular data objects. Unlike a matrix in data frame each column can contain
different modes of data. The first column can be numeric while the second column can be
character and third column can be logical. It is a list of vectors of equal length.
Data Frames are created using the [Link]() function.

Live Demo
# Create the data frame.
BMI <- [Link](
gender = c("Male", "Male","Female"),
height = c(152, 171.5, 165),
weight = c(81,93, 78),
Age = c(42,38,26)
)
print(BMI)

When we execute the above code, it produces the following result −


gender height weight Age
1 Male 152.0 81 42
2 Male 171.5 93 38
3 Female 165.0 78 26
R - Variables

A variable provides us with named storage that our programs can manipulate. A variable in R
can store an atomic vector, group of atomic vectors or a combination of many Robjects. A valid
variable name consists of letters, numbers and the dot or underline characters. The variable
name starts with a letter or the dot not followed by a number.

Variable Name Validity Reason

var_name2. valid Has letters, numbers, dot and underscore

var_name% Invalid Has the character '%'. Only dot(.) and underscore allowed.

2var_name invalid Starts with a number

valid
.var_name,
Can start with a dot(.) but the dot(.)should not be followed by a number.
[Link]

.2var_name invalid The starting dot is followed by a number making it invalid.

_var_name invalid Starts with _ which is not valid

Variable Assignment
The variables can be assigned values using leftward, rightward and equal to operator. The values
of the variables can be printed using print() or cat() function. The cat() function combines
multiple items into a continuous print output.
Live Demo

# Assignment using equal operator.


var.1 = c(0,1,2,3)

# Assignment using leftward operator.


var.2 <- c("learn","R")

# Assignment using rightward operator.


c(TRUE,1) -> var.3

print(var.1)
cat ("var.1 is ", var.1 ,"\n")
cat ("var.2 is ", var.2 ,"\n")
cat ("var.3 is ", var.3 ,"\n")
When we execute the above code, it produces the following result −
[1] 0 1 2 3
var.1 is 0 1 2 3
var.2 is learn R
var.3 is 1 1
Note − The vector c(TRUE,1) has a mix of logical and numeric class. So logical class is coerced
to numeric class making TRUE as 1.

Data Type of a Variable


In R, a variable itself is not declared of any data type, rather it gets the data type of the R - object
assigned to it. So R is called a dynamically typed language, which means that we can change a
variable’s data type of the same variable again and again when using it in a program.
Live Demo

var_x <- "Hello"


cat("The class of var_x is ",class(var_x),"\n")

var_x <- 34.5


cat(" Now the class of var_x is ",class(var_x),"\n")

var_x <- 27L


cat(" Next the class of var_x becomes ",class(var_x),"\n")

When we execute the above code, it produces the following result −


The class of var_x is character
Now the class of var_x is numeric
Next the class of var_x becomes integer

Finding Variables
To know all the variables currently available in the workspace we use the ls() function. Also the
ls() function can use patterns to match the variable names.
Live Demo

print(ls())

When we execute the above code, it produces the following result −


[1] "my var" "my_new_var" "my_var" "var.1"
[5] "var.2" "var.3" "[Link]" "var_name2."
[9] "var_x" "varname"
Note − It is a sample output depending on what variables are declared in your environment.
The ls() function can use patterns to match the variable names.
Live Demo

# List the variables starting with the pattern "var".


print(ls(pattern = "var"))

When we execute the above code, it produces the following result −


[1] "my var" "my_new_var" "my_var" "var.1"
[5] "var.2" "var.3" "[Link]" "var_name2."
[9] "var_x" "varname"
The variables starting with dot(.) are hidden, they can be listed using "[Link] = TRUE"
argument to ls() function.
Live Demo

print(ls([Link] = TRUE))

When we execute the above code, it produces the following result −


[1] ".cars" ".[Link]" ".var_name" ".varname"
".varname2"
[6] "my var" "my_new_var" "my_var" "var.1" "var.2"
[11]"var.3" "[Link]" "var_name2." "var_x"

Deleting Variables
Variables can be deleted by using the rm() function. Below we delete the variable var.3. On
printing the value of the variable error is thrown.
Live Demo

rm(var.3)
print(var.3)

When we execute the above code, it produces the following result −


[1] "var.3"
Error in print(var.3) : object 'var.3' not found
All the variables can be deleted by using the rm() and ls() function together.
Live Demo

rm(list = ls())
print(ls())

When we execute the above code, it produces the following result −


character(0)

R - Decision making
Decision making structures require the programmer to specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.
Following is the general form of a typical decision making structure found in most of the
programming languages −
R provides the following types of decision making statements. Click the following links to check
their detail.

[Link]. Statement & Description

1 if statement

An if statement consists of a Boolean expression followed by one or more statements.

2 if...else statement

An if statement can be followed by an optional else statement, which executes when the
Boolean expression is false.

3 switch statement

A switch statement allows a variable to be tested for equality against a list of values.

R - Loops
There may be a situation when you need to execute a block of code several number of times. In
general, statements are executed sequentially. The first statement in a function is executed first,
followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and the
following is the general form of a loop statement in most of the programming languages −
R programming language provides the following kinds of loop to handle looping requirements.
Click the following links to check their detail.

[Link]. Loop Type & Description

1 repeat loop

Executes a sequence of statements multiple times and abbreviates the code that manages
the loop variable.

2 while loop

Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.

3 for loop

Like a while statement, except that it tests the condition at the end of the loop body.

Loop Control Statements


Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
R supports the following control statements. Click the following links to check their detail.

[Link]. Control Statement & Description

1 break statement
Terminates the loop statement and transfers execution to the statement immediately
following the loop.

2 Next statement

The next statement simulates the behavior of R switch.

R - Functions
A function is a set of statements organized together to perform a specific task. R has a large
number of in-built functions and the user can create their own functions.
In R, a function is an object so the R interpreter is able to pass control to the function, along with
arguments that may be necessary for the function to accomplish the actions.
The function in turn performs its task and returns control to the interpreter as well as any result
which may be stored in other objects.

Function Definition
An R function is created by using the keyword function. The basic syntax of an R function
definition is as follows −
function_name <- function(arg_1, arg_2, ...) {
Function body
}

Function Components
The different parts of a function are −
• Function Name − This is the actual name of the function. It is stored in R environment as
an object with this name.
• Arguments − An argument is a placeholder. When a function is invoked, you pass a value
to the argument. Arguments are optional; that is, a function may contain no arguments.
Also arguments can have default values.
• Function Body − The function body contains a collection of statements that defines what
the function does.
• Return Value − The return value of a function is the last expression in the function body
to be evaluated.
R has many in-built functions which can be directly called in the program without defining them
first. We can also create and use our own functions referred as user defined functions.

Built-in Function
Simple examples of in-built functions are seq(), mean(), max(), sum(x) and paste(...) etc. They
are directly called by user written programs. You can refer most widely used R functions.
Live Demo
# Create a sequence of numbers from 32 to 44.
print(seq(32,44))

# Find mean of numbers from 25 to 82.


print(mean(25:82))

# Find sum of numbers frm 41 to 68.


print(sum(41:68))

When we execute the above code, it produces the following result −


[1] 32 33 34 35 36 37 38 39 40 41 42 43 44
[1] 53.5
[1] 1526

User-defined Function
We can create user-defined functions in R. They are specific to what a user wants and once
created they can be used like the built-in functions. Below is an example of how a function is
created and used.
# Create a function to print squares of numbers in sequence.
[Link] <- function(a) {
for(i in 1:a) {
b <- i^2
print(b)
}
}

Calling a Function
Live Demo

# Create a function to print squares of numbers in sequence.


[Link] <- function(a) {
for(i in 1:a) {
b <- i^2
print(b)
}
}

# Call the function [Link] supplying 6 as an argument.


[Link](6)

When we execute the above code, it produces the following result −


[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
[1] 36
Calling a Function without an Argument
Live Demo
# Create a function without an argument.
[Link] <- function() {
for(i in 1:5) {
print(i^2)
}
}

# Call the function without supplying an argument.


[Link]()

When we execute the above code, it produces the following result −


[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
Calling a Function with Argument Values (by position and by name)
The arguments to a function call can be supplied in the same sequence as defined in the function
or they can be supplied in a different sequence but assigned to the names of the arguments.
Live Demo

# Create a function with arguments.


[Link] <- function(a,b,c) {
result <- a * b + c
print(result)
}

# Call the function by position of arguments.


[Link](5,3,11)

# Call the function by names of the arguments.


[Link](a = 11, b = 5, c = 3)

When we execute the above code, it produces the following result −


[1] 26
[1] 58
Calling a Function with Default Argument
We can define the value of the arguments in the function definition and call the function without
supplying any argument to get the default result. But we can also call such functions by supplying
new values of the argument and get non default result.
Live Demo

# Create a function with arguments.


[Link] <- function(a = 3, b = 6) {
result <- a * b
print(result)
}

# Call the function without giving any argument.


[Link]()
# Call the function with giving new values of the argument.
[Link](9,5)

When we execute the above code, it produces the following result −


[1] 18
[1] 45

Lazy Evaluation of Function


Arguments to functions are evaluated lazily, which means so they are evaluated only when
needed by the function body.
Live Demo

# Create a function with arguments.


[Link] <- function(a, b) {
print(a^2)
print(a)
print(b)
}

# Evaluate the function without supplying one of the arguments.


[Link](6)

When we execute the above code, it produces the following result −


[1] 36
[1] 6
Error in print(b) : argument "b" is missing, with no default

You might also like