0% found this document useful (0 votes)
3 views

r Language1

Uploaded by

Kaviya
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

r Language1

Uploaded by

Kaviya
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 82

R-LANGUAGE

Overview
• R is a programming language and software environment for statistical analysis, graphics
representation and reporting. R was created by Ross Ihaka and Robert Gentleman at the University
of Auckland, New Zealand, and is currently developed by the R Development Core Team.

• The core of R is an interpreted computer language which allows branching and looping as well as
modular programming using functions. R allows integration with the procedures written in the C,
C++, .Net, Python or FORTRAN languages for efficiency.

• R is freely available under the GNU General Public License, and pre-compiled binary versions are
provided for various operating systems like Linux, Windows and Mac.

• R is free software distributed under a GNU-style copy left, and an official part of the GNU project
called GNU.
Evolution of R

• R was initially written by Ross Ihaka and Robert Gentleman at the Department of Statistics of
the University of Auckland in Auckland, New Zealand. R made its first appearance in 1993.
• A large group of individuals has contributed to R by sending code and bug reports.
• Since mid-1997 there has been a core group (the "R Core Team") who can modify the R source
code archive.
Features of R

• R is a well-developed, simple and effective programming language which includes conditionals,


loops, user defined recursive functions and input and output facilities.
• R has an effective data handling and storage facility,
• R provides a suite of operators for calculations on arrays, lists, vectors and matrices.
• R provides a large, coherent and integrated collection of tools for data analysis.
• Google, Face Book, Amazon for data analysis its R language used
• R provides graphical facilities for data analysis and display either directly at the computer or
printing at the papers.
Programming structures

Control Statements in R Programming


• Control statements are expressions used to control the execution and flow of the program based
on the conditions provided in the statements. These structures are used to make a decision after
assessing the variable. In this article, we’ll discuss all the control statements with the examples.
• In R programming, there are 7 types of control statements as follows:
1. if condition
2. if-else condition
3. for loop
4. while loop
5. Repeat loop
6. break statement
7. Next statement
1.If Condition

This control structure checks the expression provide in parenthesis is true or not. If true, the

execution of the statements in braces{}continues.


Syntax:
if(expression){
statements
}
Example:
x<-100
if(x>10){
print(paste( x, ” is greater than 10”))
}
Output:
[1] “100 is greater than 10”
2. If-else condition
It is similar to if condition but when the test expression in if condition fails, then
statements in else condition are executed.
Syntax:

if(expression){
statements
}
else{
statements
}
Example:
x<-5
if(x>10){
print(paste( x, ” is greater than 10”))
}else{
print(paste( x, ” is less than 10”))
}
Output:
3.For Loop
It is a type of loop or sequence of statements executed repeatedly until exit condition is
reached.
Syntax:
for(value in vector)
{
Statements
}
Example:
v<-LETTERS[1:4]
for(i in v)
{
print (i)
}
Output:
[1] “A”
[1] “B”
[1] “C”
[1] “D”
4.While loop
While loop is another kind of loop iterated until a condition is satisfied. The
testing expression is checked first before executing the body of loop.
Syntax:
while(test_expression)
{
Statements
}
Example:
v<-c(“Hello”, “while loop”)
cnt<-2
while(cnt<7)
{
print(v)
cnt=cnt+1
}
Output:

[1] “Hello” “while loop”


[1] “Hello” “while loop”
[1] “Hello” “while loop”
[1] “Hello” “while loop”
[1] “Hello” “while loop”
5.Repeat loop
Repeat is a loop which can be iterated many number of times but there is no exit condition to come
out from the loop.
Syntax:
Repeat
{
commands
if (conditions)
{
break
}
}
Example:
v<-c("Hai","Corona")
cnt<-0
repeat
{
s<-as.character(cnt)
cat(v, s,"\n")
cnt<-cnt+1
if(cnt>5)
{
break
}
}
Output:

Hai Corona 0
Hai Corona 1
Hai Corona 2
Hai Corona 3
Hai Corona 4
Hai Corona 5
6.Break statement

repeat is a loop which can be iterated many number of times but there is no exit condition to come

out from the loop. So, break statement is used to exit from the loop. break statement can be used in

any type of loop to exit from the loop.


Example:
v<-c("Hello", "loop")
cnt<-2
repeat
{
print(v)
cnt<-cnt+1
if(cnt>5)
{
break
}
}
Output:
[1] "Hello" "loop"
[1] "Hello" "loop"
[1] "Hello" "loop"
[1] "Hello" "loop"
7.Next statement
next statement is used to skip the current iteration without executing the further statements
and continues the next iteration cycle without terminating the loop
Example:
v<-LETTERS[1:6]
for(i in v)
{
if(i=="D")
{
next
}
print (i)
}
Output:

[1] "A"

[1] "B"

[1] "C"

[1] "E"

[1] "F"
Operators in R
• n computer programming, an operator is a symbol which represents an action. An operator is a
symbol which tells the compiler to perform specific logical or mathematical manipulations. R
programming is very rich in built-in operators.
• In R programming, there are different types of operator, and each operator performs a different
task. For data manipulation, There are some advance operators also such as model formula and list
indexing.
• There are the following types of operators used in R
1.Arithmetic Operators

• Arithmetic operators are the symbols which are used to represent arithmetic math operations. The
operators act on each and every element of the vector. There are various arithmetic operators which
are supported by R.

Operator Description

+ Addition
- Subtraction
* Multiplication
/ Division
^ or ** Exponentiation
x %% y Modulus
%/% Integer division
Example
a <- 16
b <- 3
add <- a + b
sub <- a - b
multi <- a * b
division <- a / b
Integer_Division <-a %/% b
exponent <-a ^ b
modulus <- a %% b
print(paste("Addition of two numbers 16 and 3 is : ", add))
print(paste("Subtracting Number 16 from 3 is : ", sub))
print(paste("Multiplication of two numbers 16 and 3 is : ", multi))
print(paste("Division of two numbers 16 and 3 is : ", division))
print(paste("Integer Division of two numbers 16 and 3 is : ", Integer_Division))
print(paste("Exponent of two numbers 16 and 3 is : ", exponent))
print(paste("Modulus of two numbers 16 and 3 is : ", modulus))
Output
a <- 16
b <- 3
add <- a + b
sub <- a - b
multi <- a * b
division <- a / b
Integer_Division <-a %/% b
exponent <-a ^ b
modulus <- a %% b
print(paste("Addition of two numbers 16 and 3 is : ", add))
[1] "Addition of two numbers 16 and 3 is : 19"
print(paste("Subtracting Number 16 from 3 is : ", sub))
[1] "Subtracting Number 16 from 3 is : 13“
print(paste("Multiplication of two numbers 16 and 3 is : ", multi))
[1] "Multiplication of two numbers 16 and 3 is : 48"
print(paste("Division of two numbers 16 and 3 is : ", division))
[1] "Division of two numbers 16 and 3 is : 5.33333333333333"
print(paste("Integer Division of two numbers 16 and 3 is : ", Integer_Division))
[1] "Integer Division of two numbers 16 and 3 is : 5"
print(paste("Exponent of two numbers 16 and 3 is : ", exponent))
[1] "Exponent of two numbers 16 and 3 is : 4096"
print(paste("Modulus of two numbers 16 and 3 is : ", modulus))
[1] "Modulus of two numbers 16 and 3 is : 1"
2. Relational Operators
Relational operators are used to compare between values. Here is a list of relational operators
available in R
Operator Description

< Less than

> Greater than

<= Less than or equal to

>= Greater than or equal to


== Equal to

!= Not equal to
Example

x <- 5
y <- 16
x<y
[1] TRUE
x>y
[1] FALSE
x<=5
[1] TRUE
y>=20
[1] FALSE
y == 16
[1] TRUE
x != 5
[1] FALSE
3. Logical Operators
Logical operators are used to carry out Boolean operations like AND, OR etc.

Operato Description
r
! Logical NOT

& Element-wise logical AND

&& Logical AND

| Element-wise logical OR

|| Logical OR
 Operators & and | perform element-wise operation producing result having length of the longer
operand.

 But && and || examines only the first element of the operands resulting into a single length logical
vector.

 Zero is considered FALSE

 non-zero numbers are taken as TRUE.


Example
x <- c(TRUE,FALSE,0,6)
y <- c(FALSE,TRUE,FALSE,TRUE)
!x
[1] FALSE TRUE TRUE FALSE

x&y
[1] FALSE FALSE FALSE TRUE

x&&y
[1] FALSE

x|y
[1] TRUE TRUE FALSE TRUE

x||y
[1] TRUE
4. Miscellaneous Operators

These R programming operators are used for special cases and are not for general mathematical or
logical computation.

operator description
: It is used to generate a series of numbers in sequence for a
vector
%in% This operator is used to check if an element belongs to a
vector or not
%*% This operator multiplies a matrix with its transpose
Example1
x <- 0:9
print(x)
Output:[1] 0 1 2 3 4 5 6 7 8 9
Example2
v1 <- 5
t <- 0:9
print(v1 %in% t)
Output:[1] TRUE
Example3
M = matrix( c(1,2,3,4), nrow = 2,ncol = 2,byrow = TRUE)
T= M %*% t(M)
print(T)
Output:
[,1] [,2]
[1,] 5 11
[2,] 11 25
Functions:

Definition

 An R function is created by using the keyword function.


 Function is a set of statement to perform a specific task.
Syntax
function_name <- function(arg_1, arg_2, ...)
{
function body
}
Function Components

• 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.
Example
#Create a sequence of numbers from 5 to 15.
print(seq(5,15))
# Find mean of numbers from 5 to 20.
print(mean(5:20))
# Find sum of numbers from 5 to 10
print(sum(5:10))
Output
[1] 5 6 7 8 9 10 11 12 13 14 15
[1] 1.4
[1] 45
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.
Calling a Function
Example
# Create a function to print squares of numbers in sequence .
new.function <- function(a) {
for(i in 1:a) {
b <- i^2
print(b)
}
}
# Call the function new.function supplying 6 as an argument.
new.function(6)
Output
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
[1] 36
Calling a Function without an Argument

Example
# Create a function without an argument.
new.function <- function() {
for(i in 1:5) {
print(i^2)
}
}
# Call the function without supplying an argument.
new.function()
Output
[1] 1
[1] 4
[1] 9
[1] 16
[1] 25
Environment and Scope Issues

• A function—formally referred to as a closure in the R documentation—consists not only of its arguments


and body but also of its environment. The latter is made up of the collection of objects present at the time
the function is created. An understanding of how environments work in R is essential for writing effective
R functions.
The Top-Level Environment
Consider this example
> w <- 12
> f <- function(y) {
+ d <- 8
+ h <- function() {
+ return(d*(w+y))
+ }
+ return(h())
+}
> environment(f)
<environment: R_GlobalEnv>
• Here, the function f() is created at the top level—that is, at the interpreter command prompt—and thus has
the top-level environment, which in R output is referred to as R_GlobalEnv but which confusingly ...
Recursion

• In programming, recursion refers to a function that calls itself. You've probably gotten an error in Excel if you
tried to do a function on the cell that you're on. In programming, this is perfectly acceptable. The only caveat is
that you have an exit point; that is, a way out of calling yourself. Otherwise, you get stuck in an endless loop.
Recursion is a way to divide and conquer complex algorithms by breaking them into successive recursive calls
to the same program.
Example 1
Factorial
factorial <- function(x) {
if(x==0)
return (1)
else
return (x * factorial (x-1))
}
factorial(10)
Output:
3628800.
Example 2

Towers of Hanoi
In the Towers of Hanoi puzzle, you are given three pegs with disks on the first peg. The object is
to move all pegs to the final peg, but you can only move one peg at a time. The highest disk
from one stack must move to another stack (and go on top); you cannot put it on a smaller disk.
tower <- function(disks, source, distination, aux) {
if(disks == 1) {
print(paste(source, ' ---->', distination))
return()
} else {
tower(disks - 1, source, aux, distination)
print(paste(source, '---->', distination))
return(tower(disks - 1, aux, distination, source))
}
}
Replacement Functions

• replace() function in R Language is used to replace the values in the specified string vector x with
indices given in list by those given in values. It takes on three parameters first is the list name, then
the index at which the element needs to be replaced, and the third parameter is the replacement
values.
Example
replace(target, index, replacement)

df <- c('apple', 'orange', 'grape', 'banana')


df

Output

"apple" "orange" "grape" "banana”

dy <- replace(df, 2, 'blueberry')


dy

Output

"apple" "blueberry" "grape" "banana"

dx <- replace(dy, 4, 'cranberry')


dx

Output

"apple" "blueberry" "grape" "cranberry"


R Data Structures

• Data structures are very important to understand. Data structure are the objects which we will
manipulate in our day-to-day basis in R. Dealing with object conversions is the most common
sources of despairs for beginners. We can say that everything in R is an object.
Vectors

• A vector is the basic data structure in R, or we can say vectors are the most basic R data objects.
There are six types of atomic vectors such as logical, integer, character, double, and raw. "A vector is
a collection of elements which is most commonly of mode character, integer, logical or
numeric" A vector can be one of the following two types:
Atomic vectors in R
In R, there are four types of atomic vectors. Atomic vectors play an important role in
Data Science. Atomic vectors are created with the help of c() function.
Example

Vector Accssing
month.abb[8]
[1] "Aug “

month.abb[c(1,3,4)]
[1] "Jan" "Mar" "Apr“

month.abb[13]
[1] NA

month.abb[4:8]
[1] "Apr" "May" "Jun" "Jul" "Aug"
Vector- Manipluation
days<-c('Mon','Tue','Wed')
weekend<-c('sat','sunday')
alldays<-c(days,weekend)
alldays
[1] "Mon" "Tue" "Wed" "sat" "sunday“

alldays<-c(days[c(1,2)],weekend)
alldays
[1] "Mon" "Tue" "sat" "sunday“

one_to_ten<-1:10
eleven_to_tewenty<-11:20
one_to_ten*2
[1] 2 4 6 8 10 12 14 16 18 20
List

• In R, the list is the container. Unlike an atomic vector, the list is not restricted to be a single mode.
A list contains a mixture of data types. The list is also known as generic vectors because the
element of the list can be of any type of R object. "A list is a special type of vector in which
each element can be a different type."
• We can create a list with the help of list() or as.list(). We can use vector() to create a required
length empty list.
List Creation
a_list<-list('abcd',123,1:10,month.abb)
a_list
[[1]]
[1] "abcd"

[[2]]
[1] 123

[[3]]
[1] 1 2 3 4 5 6 7 8 9 10

[[4]]
[1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
List Accesing
a_list[1]
[[1]]
[1] "abcd"

class(a_list[1])
[1] "list“

class(a_list[[1]])
[1] "character“

class(a_list[[2]])
[1] "numeric“

a_list[[3]]
[1] 1 2 3 4 5 6 7 8 9 10

a_list[[3]][3:7]
[1] 3 4 5 6 7

a_list[[4]]
[1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec“

a_list[[4]][c(2,3,12)]
Arrays

• There is another type of data objects which can store data in more than two dimensions known as
arrays. "An array is a collection of a similar data type with contiguous memory
allocation." Suppose, if we create an array of dimension (2, 3, 4) then it creates four rectangular
matrices of two rows and three columns.
• In R, an array is created with the help of array() function. This function takes a vector as an input
and uses the value in the dim parameter to create an array.
Syntax
array_name <- array(data, dim= (row_size, column_size, matrices, dim_names))
Array Creation
vector1<-c(5,9,3)
vector2<-c(10,11,12,13,14,15)
result<-array(c(vector1,vector2),dim=c(3,3,2))
result

,,1

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


[1,] 5 10 13
[2,] 9 11 14
[3,] 3 12 15

,,2

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


[1,] 5 10 13
[2,] 9 11 14
[3,] 3 12 15
Naming Coloumns and Rows
vector1<-c(5,9,3)
vector2<-c(10,11,12,13,14,15)
column.names<-c("col","col2","col3")
row.names<-c("row1","row2","row3")
matrix.name<-c("matrix1","matrix2")
result<-
array(c(vector1,vector2),dim=c(3,3,2),dimnames=list(row.names,column.names,matrix.name))
result
, , matrix1

col col2 col3


row1 5 10 13
row2 9 11 14
row3 3 12 15

, , matrix2

col col2 col3


row1 5 10 13
row2 9 11 14
row3 3 12 15
Array-Accessing
result[3, ,2]
col col2 col3
3 12 15

result[1,3,1]
[1] 13

result[ , ,2]
col col2 col3
row1 5 10 13
row2 9 11 14
row3 3 12 15
Matrices
A matrix is an R object in which the elements are arranged in a two-dimensional rectangular layout. In the matrix,
elements of the same atomic types are contained. For mathematical calculation, this can use a matrix containing the
numeric element. A matrix is created with the help of the matrix() function in R.
Syntax
matrix_name<-matrix(data, no_row, no_col, by_row, dim_name)
Exmaple
new_m<-matrix(data=1:12,nrow=3)
new_m
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12

new_m[ ,1]
[1] 1 2 3

new_m[1, ]
[1] 1 4 7 10

new_m[3,4]
[1] 12

new_m[2,2]
[1] 5
new_m+10
[,1] [,2] [,3] [,4]
[1,] 11 14 17 20
[2,] 12 15 18 21
[3,] 13 16 19 22

new_m*10
[,1] [,2] [,3] [,4]
[1,] 10 40 70 100
[2,] 20 50 80 110
[3,] 30 60 90 120
new_m[2,2]<-50
new_m
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 50 8 11
[3,] 3 6 9 12

new_m[2,2]<-indian
Error: object 'indian' not found

new_m
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 50 8 11
[3,] 3 6 9 12
Data Frames

• A data frame is a two-dimensional array-like structure, or we can say it is a table in which each
column contains the value of one variable, and row contains the set of value from each column.
• The column name will be non-empty.
• The row names will be unique.
• A data frame stored numeric, factor or character type data.
• Each column will contain same number of data items.
Dataframe - Creation

college<-c('CIT','GCT','PSG')
year<-c(2019,2018,2017)
db<-data.frame(college_names=college,year_since=year)
db
college_names year_since
1 CIT 2019
2 GCT 2018
3 PSG 2017
Dataframe-Accessing
db[2,2]
[1] 2018
db[2,1]
[1] "GCT“

db[ ,1]
[1] "CIT" "GCT" "PSG“
db[1, ]
college_names year_since
CIT 2019

db$college_names
[1] "CIT" "GCT" "PSG“
db$year_since
[1] 2019 2018 2017

max(db$year_since)
[1] 2019
min(db$year_since)
[1] 2017
Factors
• Factors are also data objects that are used to categorize the data and store it as levels. Factors can
store both strings and integers. Columns have a limited number of unique values so that factors are
very useful in columns. It is very useful in data analysis for statistical modeling.
• Factors are created with the help of factor() function by taking a vector as an input parameter.
Example

days<-c('Mon','Tue','Wed')
days<-c('Thu','wed','sun')
sort(days)
[1] "sun" "Thu" "wed“

days<-c('Thu','wed','sun')
week_levels<-c('mon','Tue','wed','Thu','fri','sat','sun')
days_f<-factor(days,levels=week_levels)
sort(days_f)
[1] wed Thu sun
Levels: mon Tue wed Thu fri sat sun
Classes

• Classes and Objects are basic concepts of Object-Oriented Programming that revolve around
the real-life entities. Everything in R is an object. An object is simply a data structure that has
some methods and attributes. A class is just a blueprint or a sketch of these objects. It
represents the set of properties or methods that are common to all objects of one type.
• S3 is the simplest yet the most popular OOP system and it lacks formal definition and
structure.
Example
# create a list with required components
movieList->list(name= "Iron man", leadActor= "Robert Downey Jr")
# give a name to your class
class(movieList)-> "movie"
movieList

Output:
$name
[1] "Iron man"
$leadActor
[1] "Robert Downey Jr"
Input/Output Functions in R
• Input and output functions are a programming language’s ability to talk and interact with its users.
Have a look at many such functions in R.
• we can read inputs from the user or a file using simple and easy-to-use functions. Similarly, we can
display the complex output or store it to a file using the same. R’s base package has many such
functions, and there are packages that provide functions that can do the same and process the
information in the required ways at the same time
Input Function
It any program language so you give to input during runtime. You should not assign values ,
variables the program itself.
Two types of things which takes the input during the runtime:
 Readline()
 Scan()
Readline() Scan()
Allways reads character Reads mulitple values as a vector
datatype
Readline()

syntax
1. var_name=readline()
2. var_name=readline("enter value")
3. var_name=readline("prompt=enter value")
In all the three cases read the input from the user during the runtime
 readline() reads the single values => as a character datatype
 class() is used to know the datatype of a variable (or) an object
 as.integer() will convert the data into integer datatype
1.Readline()->No parameter
Example
Code:
a = readline()
User input
10
Code:
print(a)
Output:
[1] "10"
2.Readline()->parameter used
Example1
Code:
a = readline("enter value for a: ")
User input
enter value for a: 20
Code:
print(a)
Output:
[1] " 20"
Example2
Code:
a = readline("enter value for a: ")
User input
enter value for a: 20
Code:
print(class(a))
Output:
[1] " character"
Example3
Code:
a = readline("enter value for a: ")
User input
enter value for a: 25
Code:
a=as.integer(a)
print(class(a))
Output:
[1] " integer"
3.Readline()->parameter are used prompt attributed

Code:
a = readline(prompt="enter value for a: ")
User input
enter value for a: 25
Code:
a=as.integer(a)
print(class(a))
Output:
[1] " integer"
Scan()
Scan() is used to reads multiple elements and it forms vector => does not take any parameter, so they
can users used the scan()

Example1
Code:
a = scan()
User input
10
20
30
40
50
Code:
print(a)
Output:
[1] 10 20 30 40 50
Example2
Code:
a = scan()
User input
10
20
30
40
50
Code:
print(a)

Code:
print(class(a))
Output:
[1] 10 20 30 40 50

[1] "numeric"
Output Function

To display the output of your program to the screen, you can use one of the following functions:

1. print()functions
We can use the print() function to display the output to the terminal. The print() function is a
generic function. This means that the function has a lot of different methods for different types of
objects it may need to print. The function takes an object as the argument

2. cat() function
We can also use the cat() function to display a string. The cat() function concatenates all of the
arguments and forms a single string which it then prints. For example:
Print()
Example1
Code:
a = readline("enter value for a: ")
User input
enter value for a: 67
Code:
print(a)
Output:
[1] 67
Example2
Code:
a = readline("enter value for a: ")
User input
enter value for a: 10
Code:
print("a=",a)
Output:
[1] "a="
Example3
Code:
a = readline("enter value for a: ")
User input
enter value for a: 67
Code:
print("welcome to R")
Output:
[1] welcome to R
cat()
Example1
Code:
a = readline("enter value for a: ")
User input
enter value for a: 34
Code:
cat("a=",a)
Output:
[1] a=34
Example2
Code:
a = readline("enter value for a: ")
User input
enter value for a: 67
Code:
cat(a)
Output:
[1] 34
String Manipulation in R:

• We will take a look at the string manipulation functions in R programming. String manipulation
functions are the functions that allow creation and modification of strings in R.
• The string manipulation functions available in R’s base packages. We are going to look at these
functions in detail.
1. The nchar function
2. The to upper function
3. The to lower function
4. The substr function
5. The grep function
6. The paste function
7. The strsplit function
8. The sprintf function
9. The cat function
10. The sub function
1.The nchar function
The nchar() function takes a character vector as the input and returns a vector that contains the sizes of
all the elements inside the character vector. Here the syntax for the nchar function.

Syntax

nchar(x, type = ”char”, allowNA = FALSE, keepNA = NA )

Where x is a character vector,


type sets what type of data is stored inside the input vector, by default, its value is set to “char”,
allowNA is a boolean that decides whether NA values should be returned for elements in the input
vector that are invalid,
keepNA is a boolean that decides whether NA values should be returned when elements inside the input
vector are NA
Here is an example of the usage of the nchar function
code
string <- "Hello My Name Is TechVidvan“
nchar(string)
strvec <- c(string,"HI", "hey", "haHa")
nchar(strvec)
Output:
2. The toupper function

The toupper() function, as the name suggests, turns the input character vector to upper case. The syntax
of the toupper function is very simple.

Syntax

toupper()

Where x is the input character vector.


Here is an example of the usage of the toupper function.

Code:
toupper(string)
toupper(strvec)
Output:

You might also like