Introduction to R Programming Basics
Introduction to R Programming Basics
Introduction
The R Language stands out as a powerful tool in the modern era of statistical
computing and data analysis. Widely embraced by statisticians, data scientists, and
researchers, the R Language offers an extensive suite of packages and libraries tailored
for data manipulation, statistical modeling, and visualization. In this article, we explore
the features, benefits, and applications of the R Programming Language, shedding light
on why it has become an indispensable asset for data-driven professionals across
various industries.
Although the professors started working on R in the early 90s, version 1.0.0 wasn’t
officially released until February 2000.
Features of R Programming Language
The R Language is renowned for its extensive features that make it a powerful tool for
data analysis, statistical computing, and visualization. Here are some of the key features
of R:
5. Platform Independence:
R is platform-independent, running on various operating systems, including
Windows, macOS, and Linux, which ensures flexibility and ease of use across
different environments.
Applications of R language
We use R for Data Science. It gives us a broad variety of libraries related to
statistics. It also provides the environment for statistical computing and design.
R is used by many quantitative analysts as its programming tool. Thus, it helps in
data importing and cleaning.
R is the most prevalent language. So many data analysts and research
programmers use it. Hence, it is used as a fundamental tool for finance.
Tech giants like Google, Facebook, Bing, Twitter, Accenture, Wipro, and many more
using R nowadays.
Step 1: First, you need to set up an R environment in your local machine. You can
download the same from [Link].
Install R and R Studio
You have to download both the applications first go with R Base and then install
RStudio. after click on install R you will get a new page like this.
Install R and R Studio
Here we can select the linux,mac or windows any one according to users system. you
have to click on for which you want to install.
now click on the link show above in image so R base start downloading and after again
go to main page and download and click on Install RStudio.
Step 3: After downloading, you will get a file named “[Link]” in your
Downloads folder.
8. Environmental Science
Climate Modeling: R is used to model climate change scenarios, analyze
temperature trends, and predict future climate conditions.
Ecology and Conservation: R helps analyze biodiversity, population dynamics, and
environmental conservation data.
Sustainability Research: Environmental agencies use R to assess sustainable
resource usage and track environmental impacts.
9. Sports Analytics
Performance Analysis: Teams use R for analyzing player statistics, improving
strategies, and optimizing performance in various sports.
Game Prediction Models: R is used to predict outcomes of sports events based on
historical data, player performance, and other variables.
R's extensive libraries, rich functionality, and integration capabilities with other tools
make it a versatile language for a wide range of professional fields. Its open-source
nature also fosters innovation and collaboration across different industries.
Variables in R
A variable is a memory allocated for the storage of specific data and the name
associated with the variable is used to work around this reserved block.
The name given to a variable is known as its variable name. Usually a single variable
stores only the data belonging to a certain data type.
The name is so given to them because when the program executes there is subject to
change hence it varies from time to time.
Using equal operator- operators use an arrow or an equal sign to assign values to
variables.
Using the leftward operator- data is copied from right to left.
Using the rightward operator- data is copied from left to right.
1. class() function
This built-in function is used to determine the data type of the variable provided to it.
The R variable to be checked is passed to this as an argument and it prints the data
type in return.
Syntax
class(variable)
Example
var1 = "hello"
print(class(var1))
Output
[1] "character"
2. ls() function
This built-in function is used to know all the present variables in the workspace. This is
generally helpful when dealing with a large number of variables at once and helps
prevents overwriting any of them.
Syntax
ls()
Example
var1 = "hello"
print(ls())
Output
This is again a built-in function used to delete an unwanted variable within your
workspace. This helps clear the memory space allocated to certain variables that are
not in use thereby creating more space for others. The name of the variable to be
deleted is passed as an argument to it.
Syntax
rm(variable)
Example
var1 = "hello"
# Removing variable
rm(var3)
print(var3)
Output
1. Global Variables
Global variables are those variables that exist throughout the execution of a program. It
can be changed and accessed from any part of the program.
As the name suggests, Global Variables can be accessed from any part of the program.
Global variables are usually declared outside of all of the functions and blocks. They
can be accessed from any portion of the program.
# global variable
global = 5
# within a function
display = function(){
print(global)
display()
global = 10
display()
Output
[1] 5
[1] 10
In the above code, the variable ‘global’ is declared at the top of the program outside all
of the functions so it is a global variable and can be accessed or updated from
anywhere in the program.
2. Local Variables
Local variables are those variables that exist only within a certain part of a program like
a function and are released when the function call ends. Local variables do not exist
outside the block in which they are declared, i.e. they can not be accessed or used
outside that block.
func = function(){
age = 18
print(age)
cat("Age is:\n")
func()
Output
Age is:
[1] 18
Types of R Variables
Depending on the type of data that you want to store, variables can be divided into the
following types.
1. Boolean Variables
It stores single bit data which is either TRUE or FALSE. Here, TRUE means yes
a = TRUE
print(a)
print(class(a))
Output
[1] TRUE
[1] "logical"
Here, we have declared the boolean variable a with the value TRUE. Boolean variables
2. Integer Variables
A = 14L
print(A)
print(class(A))
Output
[1] 14
[1] "integer"
Here, L represents integer value. In R, integer variables belong to the integer class
x = 13.4
print(x)
print(class(x))
Output
[1] 13.4
[1] "numeric"
Here, we have created a floating point variable named x. You can see that the floating
4. Character Variables
alphabet = "a"
print(alphabet)
print(class(alphabet))
Output
[1] "a"
[1] "character"
Here, we have created a character variable named alphabet. Since character variables
5. String Variables
It stores data that is composed of more than one character. We use double quotes to
represent string data. For example,
print(message)
print(class(message))
Output
[1] "character"
Here, we have created a string variable named message. You can see that the string
variable also belongs to the character class.
Depending on the conditions or information passed into the program, you can change
the value of a variable. For example,
print(message)
# changing value of a variable
print(message)
Output
In this program,
You can see that the value of a variable can be changed anytime.
R Constants
Constants are those entities whose values aren't meant to be changed anywhere
throughout the code. In R, we can declare constants using the <- symbol. For example,
print(x)
Output
Types of R Constants
In R, we have the following types of constants.
In addition to these, there are 4 specific types of R constants - Null, NA, Inf, NaN.
1. Integer Constants
Integer constants are the integer values we use in our code. These constants end with the
x <- 15L
print(typeof(x))
print(class(x))
Output
[1] "integer"
[1] "integer"
Here, 15L is a constant which has been assigned to x. You can see that the type and class
We can use different types of integer constants in our code. For example,
# hexadecimal value
x <- 0x15L
print(x)
# exponential value
x <- 1e5L
print(x)
Output
[1] 21
[1] 100000
2. Numeric Constants
z <- 3e-3
print(z) # 0.003
print(class(z)) # "numeric"
y <- 3.4
print(y) # 3.4
print(class(z)) # "numeric"
Output
[1] 0.003
[1] "numeric"
[1] 3.4
[1] "numeric"
3. Logical Constants
x <- TRUE
y <- FALSE
print(x)
print(y)
Output
[1] TRUE
[1] FALSE
Note: We can also use a single character to create logical constants. For example,
x <- T
print(x) # TRUE
4. String Constants
String constants are the string data we use in our code. For example,
print(message)
Output
5. Complex Constants
A complex constant is data that contains a real and an imaginary part (denoted by the
y <- 3.2e-1i
print(y)
print(typeof(y))
Output
[1] 0+0.32i
[1] "complex"
y <- 3i
print(y) # 0+3i
print(typeof(y)) # "complex"
Special R Constants
R programming also provides 4 special types of constants.
print(typeof(x)) # "NULL"
a <- 2^2020
print(a) # Inf
b <- -2^2020
print(b) # -Inf
print(Inf/Inf) # NaN
print(NA + 20) # NA
Built-In R Constants
R programming provides some predefined constants that can be directly used in our
program. For example,
print(LETTERS)
# print list of lowercase letters
print(letters)
print([Link])
print(pi)
Output
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
[1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
[1] 3.141593
R Operators
Operators are the symbols directing the compiler to perform various kinds of operations
between the operands. Operators simulate the various mathematical, logical, and decision
operations performed on a set of Complex Numbers, Integers, and Numericals as input
operands.
R supports majorly four kinds of binary operators between a set of operands. In this
article, we will see various types of operators in R Programming language and their
usage.
Arithmetic Operators
Arithmetic Operators modulo using the specified operator between operands, which may
be either scalar values, complex numbers, or vectors. The R operators are performed
element-wise at the corresponding positions of the vectors.
The values at the corresponding positions of both operands are added. Consider the
following R operator snippet to add two vectors:
b <- c (2.33, 4)
print (a+b)
The second operand values are subtracted from the first. Consider the following R
operator snippet to subtract two variables:
a <- 6
b <- 8.4
print (a-b)
Output : -2.4
B= c(4,4)
C= c(5,5)
print (B*C)
Output : 20 20
The first operand is divided by the second operand with the use of the ‘/’ operator.
a <- 10
b <- 5
print (a/b)
Output : 2
a <- 4
b <- 5
print(a^b)
Output : 1024
The remainder of the first operand divided by the second operand is returned.
list2<-c(2,4)
print(list1 %% list2)
Output : 0 2
The following R code illustrates the usage of all Arithmetic R operators.
Output
Addition of vectors : 2 5
Subtraction of vectors : -2 -1
Multiplication of vectors : 0 6
Modulo of vectors : 0 2
Power operator : 0 8
Logical Operators
Logical Operators in R simulate element-wise decision operations, based on the specified
operator between the operands, which are then evaluated to either a True or False
boolean value. Any non-zero integer value is considered as a TRUE value, be it a complex
or real number.
Element-wise Logical AND operator (&)
Any non zero integer value is considered as a TRUE value, be it complex or real
number.
print(list1|list2)
A unary operator that negates the status of the elements of the operand.
print(!list1)
Returns True if both the first elements of the operands are True.
Output : FALSE
print(list1[1]||list2[1])
Output : TRUE
Output
Logical OR : TRUE
Returns TRUE if the corresponding element of the first operand is less than that of the
second operand. Else returns FALSE.
print(list1<list2)
Returns TRUE if the corresponding element of the first operand is less than or equal to
that of the second operand. Else returns FALSE.
Returns TRUE if the corresponding element of the first operand is greater than that of the
second operand. Else returns FALSE.
Returns TRUE if the corresponding element of the first operand is greater or equal to that
of the second operand. Else returns FALSE.
Returns TRUE if the corresponding element of the first operand is not equal to the second
operand. Else returns FALSE.
print(list1!=list2)
cat ("Vector1 less than Vector2 :", vec1 < vec2, "\n")
cat ("Vector1 less than equal to Vector2 :", vec1 <= vec2, "\n")
cat ("Vector1 greater than Vector2 :", vec1 > vec2, "\n")
cat ("Vector1 greater than equal to Vector2 :", vec1 >= vec2, "\n")
Output
Assignment Operators
Assignment Operators in R are used to assigning values to various data objects in R. The
objects may be integers, vectors, or functions. These values are then stored by the
assigned variable names. There are two kinds of assignment operators: Left and Right
print (vec1)
print (vec1)
vec4 = c(2:5)
Output
vector 1 : 2 3 4 5
vector 2 : 2 3 4 5
vector 3 : 2 3 4 5
vector 4 : 2 3 4 5
vector 5 : 2 3 4 5
Miscellaneous Operators
Miscellaneous Operator are the mixed operators in R that simulate the printing of
sequences and assignment of vectors, either left or right-handed.
%in% Operator
Checks if an element belongs to a list and returns a boolean value TRUE if the value is
present else FALSE.
Output : TRUE
Checks for the value 0.1 in the specified list. It exists, therefore, prints
TRUE.
%*% Operator
This operator is used to multiply a matrix with its transpose. Transpose of the matrix is
obtained by interchanging the rows to columns and columns to rows. The number of
columns of the first matrix must be equal to the number of rows of the second matrix.
Multiplication of the matrix A with its transpose, B, produces a square
matrix. Ar∗cxBc∗r−>Pr∗r Ar∗cxBc∗r−>Pr∗r
mat = matrix(c(1,2,3,4,5,6),nrow=2,ncol=3)
print (mat)
print( t(mat))
print(pro)
Input :
[1,] 1 3 5
[2,] 2 4 6
[1,] 1 2
[2,] 3 4
[3,] 5 6
[1,] 35 44
[2,] 44 56
print(mat)
print("Product of matrices")
print(product,)
Output
[1,] 1 2 3 4
[,1]
[1,] 30
var <- 30
1. numeric – (3,6.7,121)
2. Integer – (2L, 42L; where ‘L’ declares this as an integer)
3. logical – (‘True’)
4. complex – (7 + 5i; where ‘i’ is imaginary number)
5. character – (“a”, “B”, “c is third”, “69”)
6. raw – ( [Link](55); raw creates a raw vector of the specified length)
R Programming language has the following basic R-data types and the following table
shows the data type and the values that each data type can take.
Basic Data Types Values Examples
“a”, “b”, “c”, …, “@”, “#”, “$”, …., “1”, "character_value <- "Hello
Character
“2”, …etc Geeks"
Decimal values are called numeric in R. It is the default R data type for numbers in R. If
you assign a decimal value to a variable x as follows, x will be of numeric type. Real
numbers with a decimal point are represented using this data type in R. It uses a format
for double-precision floating-point numbers to represent numerical values.
x = 5.6
print(class(x))
print(typeof(x))
Output
[1] "numeric"
[1] "double"
y=5
print(class(y))
print(typeof(y))
Output
[1] "numeric"
[1] "double"
When R stores a number in a variable, it converts the number into a “double” value or a
decimal type with at least two decimal places.
This means that a value such as “5” here, is stored as 5.00 with a type of double and a
class of numeric. And also y is not an integer here can be confirmed with
the [Link]() function.
y=5
# is y an integer?
print([Link](y))
Output
[1] FALSE
You can create as well as convert a value into an integer type using
the [Link]() function.
You can also use the capital ‘L’ notation as a suffix to denote that a particular value is of
the integer R data type.
x = [Link](5)
print(class(x))
print(typeof(x))
y = 5L
print(class(y))
print(typeof(y))
Output
[1] "integer"
[1] "integer"
[1] "integer"
[1] "integer"
R has logical data types that take either a value of true or false.
# Sample values
x=4
y=3
z=x>y
print(z)
print(class(z))
print(typeof(z))
Output
[1] TRUE
[1] "logical"
[1] "logical"
R supports complex data types that are set of all the complex numbers. The complex data
type is to store numbers with an imaginary component.
# Assign a complex value to x
x = 4 + 3i
print(class(x))
print(typeof(x))
Output
[1] "complex"
[1] "complex"
R supports character data types where you have all the alphabets and special characters.
It stores character values or strings. Strings in R can contain alphabets, numbers, and
symbols.
The easiest way to denote that a value is of character type in R data type is to wrap the
value inside single or double inverted commas.
char = "Geeksforgeeks"
print(class(char))
print(typeof(char))
Output
[1] "character"
[1] "character"
There are several tasks that can be done using R data types. Let’s understand each task
with its action and the syntax for doing the task along with an R code to illustrate the
task.
To save and work with data at the byte level in R, use the raw data type. By displaying a
series of unprocessed bytes, it enables low-level operations on binary data. Here are
some speculative data on R’s raw data types:
print(x)
Output
[1] 01 02 03 04 05
Five elements make up this raw vector x, each of which represents a raw byte value.
Syntax
class(object)
Example
# Logical
print(class(TRUE))
# Integer
print(class(3L))
# Numeric
print(class(10.5))
# Complex
print(class(1+2i))
# Character
print(class("12-04-2020"))
Output
[1] "logical"
[1] "integer"
[1] "numeric"
[1] "complex"
[1] "character"
Type verification
You can verify the data type of an object, if you doubt about it’s data type. To do that, you
need to use the prefix “is.” before the data type as a command.
Syntax:
is.data_type(object)
Example
# Logical
print([Link](TRUE))
# Integer
print([Link](3L))
# Numeric
print([Link](10.5))
# Complex
print([Link](1+2i))
# Character
print([Link]("12-04-2020"))
print([Link]("a"))
print([Link](2+3i))
Output
[1] TRUE
[1] TRUE
[1] TRUE
[1] TRUE
[1] TRUE
[1] FALSE
[1] FALSE
In some circumstances, the coercion is implicit, which means that the language will
change one type to another without the programmer having to expressly request it.
Syntax
as.data_type(object)
Note: All the coercions are not possible and if attempted will be returning an “NA” value.
Example
# Logical
print([Link](TRUE))
# Integer
print([Link](3L))
# Numeric
print([Link](10.5))
# Complex
print([Link](1+2i))
# Can't possible
print([Link]("12-04-2020"))
Output
R – Objects
Every programming language has its own data types to store values or any information
so that the user can assign these data types to the variables and perform operations
respectively. Operations are performed accordingly to the data [Link] data types
can be character, integer, float, long, etc. Based on the data type, memory/storage is
allocated to the variable. For example, in C language character variables are assigned
with 1 byte of memory, integer variable with 2 or 4 bytes of memory and other data
types have different memory allocation for them. Unlike other programming languages,
variables are assigned to objects rather than data types in R programming.
Type of Objects
Vectors
Atomic vectors are one of the basic types of objects in R programming. Atomic vectors
can store homogeneous data types such as character, doubles, integers, raw, logical,
and complex. A single element variable is also said to be vector.
Example:
# Create vectors
x <- c(1, 2, 3, 4)
z <- 5
print(x)
print(class(x))
print(y)
print(class(y))
print(z)
print(class(z))
Output:
[1] 1 2 3 4
[1] "numeric"
[1] "character"
[1] 5
[1] "numeric"
Lists
List is another type of object in R programming. List can contain heterogeneous data
types such as vectors or another lists.
Example:
# Create list
print(ls)
print(class(ls))
Output:
[[1]]
[1] 1 2 3 4
[[2]]
[[2]][[1]]
[1] "a"
[[2]][[2]]
[1] "b"
[[2]][[3]]
[1] "c"
[1] "list"
Matrices
To store values as 2-Dimensional array, matrices are used in R. Data, number of rows
and columns are defined in the matrix() function.
Syntax:
Example:
x <- c(1, 2, 3, 4, 5, 6)
# Create matrix
print(mat)
print(class(mat))
Output:
[, 1] [, 2] [, 3]
[1, ] 1 3 5
[2, ] 2 4 6
[1] "matrix"
Factors
Factor object encodes a vector of unique elements (levels) from the given data vector.
Example:
# Create vector
"spring", "autumn")
print(factor(s))
print(nlevels(factor(s)))
Output:
[1] 4
Arrays
array()function is used to create n-dimensional array. This function takes dim attribute
as an argument and creates required length of each dimension as specified in the
[Link]:
Example:
print(arr)
Output:
,, 1
[, 1] [, 2] [, 3]
[1, ] 1 1 1
[2, ] 2 2 2
[3, ] 3 3 3,, 2
[, 1] [, 2] [, 3]
[1, ] 1 1 1
[2, ] 2 2 2
[3, ] 3 3 3,, 3
[, 1] [, 2] [, 3]
[1, ] 1 1 1
[2, ] 2 2 2
[3, ] 3 3 3
Data Frames
Data frames are 2-dimensional tabular data object in R programming. Data frames
consists of multiple columns and each column represents a vector. Columns in data
frame can have different modes of data unlike matrices.
Example:
# Create vectors
x <- 1:5
y <- LETTERS[1:5]
df <- [Link](x, y, z)
print(df)
Output:
x y z
1 1 A Albert
2 2 B Bob
3 3 C Charlie
4 4 D Denver
5 5 E Elie
In R language readline() method takes input in string format. If one inputs an integer
then it is inputted as a string, lets say, one wants to input 255, then it will input
as “255”, like a string. So one needs to convert that inputted value to the format that he
needs. In this case, string “255” is converted to integer 255. To convert the inputted
value to the desired data type, there are some functions in R,
Syntax: var = readline(); var = [Link](var);Note that one can use “<-“ instead of “=”
Example:
var = readline();
var = [Link](var);
print(var)
Output:
255
[1] 255
Taking multiple inputs in R language is same as taking single input, just need to define
multiple readline() for inputs. One can use braces for define multiple readline() inside
it.
Syntax: var1 = readline(“Enter 1st number : “); var2 = readline(“Enter 2nd number :
“); var3 = readline(“Enter 3rd number : “); var4 = readline(“Enter 4th number : “);or,{ var1
= readline(“Enter 1st number : “); var2 = readline(“Enter 2nd number : “); var3 =
readline(“Enter 3rd number : “); var4 = readline(“Enter 4th number : “); }
Example:
# using braces
var1 = [Link](var1);
var2 = [Link](var2);
var3 = [Link](var3);
var4 = [Link](var4);
Output:
[1] 54
To take string input is the same as an integer. For “String” one doesn’t need to convert
the inputted data into a string because R takes input as string always. And for
“character”, it needs to be converted to ‘character’. Sometimes it may not cause any
error. One can take character input as same as string also, but that inputted data is of
type string for the entire program. So the best way to use that inputted data as
‘character’ is to convert the data to a character.
Example:
# string input
# character input
# convert to character
var2 = [Link](var2)
# printing values
print(var1)
print(var2)
Output:
[1] "GeeksforGeeks"
[1] "G"
Another way to take user input in R language is using a method, called scan() method.
This method takes input from the console. This method is a very handy method while
inputs are needed to taken quickly for any mathematical calculation or for any dataset.
This method reads data in the form of a vector or list.
Syntax: x = scan()
scan() method is taking input continuously, to terminate the input process, need to
press Enter key 2 times on the console.
Example: This is simple method to take input using scan() method, where some integer
number is taking as input and print those values in the next line on the console.
x = scan()
print(x)
Output:
1: 1 2 3 4 5 6
7: 7 8 9 4 5 6
13:
Read 12 items
[1] 1 2 3 4 5 6 7 8 9 4 5 6
Explanation: Total 12 integers are taking as input in 2 lines when the control goes to
3rd line then by pressing Enter key 2 times the input process will be terminated.
To take double, string, character types inputs, specify the type of the inputted value in
the scan() method. To do this there is an argument called what, by which one can
specify the data type of the inputted value.
d = scan(what = double())
c = scan(what = character())
print(d) # double
print(s) # string
print(c) # character
Output:
4: 741.25 855.36
6:
Read 5 items
8:
Read 7 items
1: g e e k s f o
8: r g e e k s
14:
Read 13 items
[1] "g" "e" "e" "k" "s" "f" "o" "r" "g" "e" "e" "k" "s"
To read file using scan() method is same as normal console input, only thing is that, one
needs to pass the file name and data type to the scan() method.
Example:
print(s) # string
print(d) # double
print(c) # character
Output:
Read 7 items
Read 5 items
Read 13 items
[1] "g" "e" "e" "k" "s" "f" "o" "r" "g" "e" "e" "k" "s"
Save the data file in the same location where the program is saved for better access.
Otherwise total path of the file need to defined inside the scan() method.
R Built-in Functions
The functions which are already created or defined in the programming framework are
known as a built-in function. R has a rich set of functions that can be used to perform almost
every task for the user. These built-in functions are divided into the following categories based
on their functionality.
Math Functions
R provides the various mathematical functions to perform the mathematical calculation.
These mathematical functions are very helpful to find absolute value, square value and much
more calculations. In R, there are the following functions which are used:
S. No Function Description Example
x<- -4
x<- 4
print(sqrt(x))
2. sqrt(x) It returns the square root of input x.
Output
[1] 2
x<- 4.5
[1] 5
x<- 2.5
[1] 2
x<- c(1.2,2.5,8.1)
print(trunc(x))
5. trunc(x) It returns the truncate value of input
x.
Output
[1] 1 2 8
x<- -4
print(abs(x))
6. round(x, digits=n) It returns round value of input x.
Output
4
x<- 4
print(cos(x))
print(sin(x))
[2] -0.7568025
[3] 1.157821
x<- 4
[1] 1.386294
x<- 4
print(log10(x))
It returns common logarithm of
9. log10(x) input x.
Output
[1] 0.60206
x<- 4
print(exp(x))
10. exp(x) It returns exponent.
Output
[1] 54.59815
String Function
R provides various string functions to perform tasks. These string functions allow us to extract
sub string from string, search pattern etc. There are the following string functions in R:
S. No Function Description Example
a <- "987654321"
pattern<- '^abc'
grep(pattern, x ,
2. [Link]=FALSE, It searches for pattern in x. print(grep(pattern, st1))
fixed=FALSE)
Output
[1] 1 3
paste('one',2,'three',4,'five')
It concatenates strings after
4. paste(..., sep="") using sep string to separate Output
them.
[1] one 2 three 4 five
print(strsplit(a, ""))
It splits the elements of
5. strsplit(x, split) character vector x at split Output
point.
[[1]]
st1<- "shuBHAm"
print(tolower(st1))
6. tolower(x) It is used to convert the
string into lower case.
Output
[1] shubham
st1<- "shuBHAm"
print(toupper(st1))
7. toupper(x) It is used to convert the
string into upper case. Output
[1] SHUBHAM
[Link]()
[Link]()
y <- rnorm(40)
png(file="[Link]")
It is used to generate random
4. rnorm(n, m=0, sd=1) numbers whose distribution is hist(y, main="Normal
Distribution")
normal.
[Link]()
[Link]()
dpois(a=2,
lambda=3)+dpois(a=3,
it is the probability of x lambda=3)+dpois(z=4,
successes in a period when the labda=4)
9. dpois(x, lamba) expected number of events is
lambda (λ) Output
[1] 0.616115
ppois(q=4, lambda=3,
[Link]=TRUE)-ppois(q=1,
It is a cumulative probability of lambda=3, [Link]=TRUE)
10. ppois(q, lamba) less than or equal to q
successes. Output
[1] 0.6434504
15. runif(x, min=0, max=1) It generates random deviates. runif(x, min=0, max=1)
a<-c(0:10, 40)
xm<-mean(a)
mean(x, trim=0, It is used to find the mean for print(xm)
1. [Link]=FALSE) x object
Output
[1] 7.916667
a<-c(0:10, 40)
xm<-sd(a)
It returns standard deviation
2. sd(x) of an object. print(xm)
Output
[1] 10.58694
a<-c(0:10, 40)
xm<-meadian(a)
Output
[1] 5.5
a<-c(0:10, 40)
xm<-range(a)
Output
[1] 0 40
a<-c(0:10, 40)
xm<-sum(a)
xm<-diff(a)
[1] 1 1 1 1 1 1 1 1 1 1 30
a<-c(0:10, 40)
xm<-min(a)
Output
[1] 0
a<-c(0:10, 40)
xm<-max(a)
Output
[1] 40
a <- matrix(1:9,3,3)
scale(x)
Output
[,1]
[1,] -0.747776547
[2,] -0.653320562
[3,] -0.558864577
[4,] -0.464408592
[5,] -0.369952608
[8,] -0.086584653
[9,] 0.007871332
[10,] 0.102327317
[11,] 0.196783302
[12,] 3.030462849
attr(,"scaled:center")
[1] 7.916667
attr(,"scaled:scale")
[1] 10.58694
R Vectors
R Vectors are the same as the arrays in R language which are used to hold multiple data
values of the same type. One major key point is that in R Programming Language the
indexing of the vector will start from ‘1’ and not from ‘0’. We can create numeric vectors
and character vectors as well.
Creating a vector
A vector is a basic data structure that represents a one-dimensional array. to create a
array we use the “c” function which the most common method use in R Programming
Language.
# R program to create Vectors we can use the c function to combine the values as a vector. By default the type will be
double
Z<- 2:7
cat('using colon', Z)
Output:
Types of R vectors
Vectors are of different types which are used in R. Following are some of the types of
vectors:
Numeric vectors
Numeric vectors are those which contain numeric values such as integer, float, etc.
# R program to create numeric Vectors creation of vectors using c() function.
v1<- c(4, 5, 6, 7)
typeof(v1)
typeof(v2)
Output:
Character vectors
# R program to create Character Vectors by default numeric values are converted into characters
typeof(v1)
Output:
[1] "character"
Logical vectors
Logical vectors in R contain Boolean values such as TRUE, FALSE and NA for Null
values.
# R program to create Logical Vectors Creating logical vector using c() function
typeof(v1)
Output:
[1] "logical"
Length of R vector
In R, the length of a vector is determined by the number of elements it contains. we can
use the length() function to retrieve the length of a vector.
x <- c(1, 2, 3, 4, 5)
length(x)
length(y)
length(z)
Output:
Note: Vectors in R are 1 based indexing unlike the normal C, python, etc format.
Output:
Modifying a R vector
Modification of a Vector is the process of applying some operation on an individual
element of a vector to change its value in the vector. There are different ways through
which we can modify a vector:
# R program to modify elements of a Vector
# Creating a vector
X<- c(2, 7, 9, 7, 8, 2)
X[3] <- 1
X[2] <-9
X[1:5]<- 0
cat('combine() function', X)
Output:
Deleting a R vector
Deletion of a Vector is the process of deleting all of the elements of the vector. This can be
done by assigning it to a NULL value.
# R program to delete a Vector
# Creating a Vector
M<- NULL
cat('Output vector', M)
Output:
# Creation of Vector
A<- sort(X)
cat('descending order', B)
Output:
ascending order 1 2 2 7 8 11descending order 11 8 7 2 2 1
Vector arithmetic
Vector arithmetic in R programming refers to performing element-wise operations on
vectors. R is designed to handle vectorized operations efficiently, so you can perform
arithmetic without explicit loops. Here's a quick overview:
# Example vectors
x <- c(1, 2, 3)
y <- c(4, 5, 6)
# Addition
x+y # Output: 5 7 9
# Subtraction
x - y # Output: -3 -3 -3
# Multiplication
x * y # Output: 4 10 18
# Division
# Modulus (remainder)
x %% y # Output: 1 2 3
# Exponentiation
x^2 # Output: 1 4 9
# Adding a scalar
x + 2 # Output: 3 4 5
# Multiplying by a scalar
x * 3 # Output: 3 6 9
3. Recycling Rule
When vectors of unequal lengths are used, the shorter one is recycled.
x <- c(1, 2, 3)
y <- c(4, 5)
# Recycling y
4. Logical Operations
x <- c(1, 2, 3)
y <- c(2, 2, 2)
# Comparison
5. Functions on Vectors
# Sum
sum(x) # Output: 6 (1 + 2 + 3)
# Mean
mean(x) # Output: 2
# Cumulative sum
cumsum(x) # Output: 1 3 6
# Dot product
sum(x * y) # Output: 12
Notes: