Numeric and Character Functions in R – Syntax and Example
1. Objective – Numeric and Character Functions
In this tutorial, we will learn what is built functions in R . As we learn what is built-in functions we will move further to learn different types of R numeric and character functions. Along with this, we will also go to learn different types of properties of character function.
So, let’s start R Numeric and Character Functions tutorial.
2. R Built-in Function
We use Built-in Functions in R to do almost everything in R. Here I’m only referring to numeric and character functions that are used in creating or recording variables.
3. R Numeric Functions
Let us see R Numeric functions:
abs(x) absolute value
ceiling(x) ceiling(3.475) is 4
sqrt(x) square root
floor(x) floor(3.475) is 3
log(x) natural logarithm
trunc(x) trunc(5.99) is 5
round(x, digits=n) round(3.475, digit=2) is 3.48
log10(x) common logarithm
signif(x, digits=n) signif(3.475, digit=2) is 3.5
cos(x), sin(x), tan(x) also acos(x), cosh(x), acosh(zx) etc
4. Character Functions in R
Let us see various R character functions:
a. grep(pattern, x , ignore.case=FALSE, fixed=FALSE)
Search for a pattern in x.
If fixed =FALSE then the pattern is a regular expression;
If fixed=TRUE then the pattern is a text string;
Returns matching indices.
grep(“A”, c(“b”,”A”,”c”), fixed=TRUE) returns 2
b. substr(x, start=n1, stop=n2)
Extract or replace substrings in a character vector.
x <- “abcdef”
substr(x, 2, 4) is “bcd”
substr(x, 2, 4) <- “22222” is “a222ef”
c. strsplit(x, split)
Split the elements of character vector x at split.
strsplit(“abc”, “”) returns 3 element vector “a”,”b”,”c”
d. sub(pattern, replacement, x, ignore.case =FALSE, fixed=FALSE)
Find a pattern in x and replace with the replacement text;
If a fixed=FALSE then a pattern is a regular expression;
If fixed = T then a pattern is a text string.
sub(“\\s”,”.”,”Hello There”) returns “Hello.There”
g. paste(…, sep=””)
Concatenate strings after using sep string to separate them.
paste(“x”,1:3,sep””) returns c(“x1”,”x2”,”x3”)
paste(“x”,1:3,sep=”M”) returns c(“xM1”,”xM2” “xM3”)
paste(“Today is”, date())
5. R Character Function – Create Strings
In R, we use to store strings in a character vector. We can create strings with a single quote / double quote.
For Example, y = “ I Love Dancing”
a. Convert object into character type
We use an as.character function that converts arguments to a character type.
For Example – we are storing 20 as a character
Y = as.character(20)
The class(Y) returns character as 20 is stored as a character in above code.
b. Check the character type
X = “ I Love Dancing”
Like is.character function, there are other functions such as is.numeric, is.integer and is.array for checking numeric vector, integer, and an array.
c. Concatenate Strings in R
The paste function is used to join two strings. It is one of the most important strings manipulation task. Every analyst performs it almost daily to structure data.
Paste Function Syntax
paste (objects, sep = ” “, collapse = NULL)
The sep= keyword denotes a separator or delimiter. The default separator is a single space. The collapse= keyword is used to separate the results.
x = “Ritika”
Output: Ritika Joshi
paste(x, y, sep = “,”)
Output: Ritika, Joshi
d. String Formatting in R
Suppose the value is being stored infraction and you need to convert it to percent. The sprintf is used to perform C-style string formatting.
Sprintf Function Syntax
The keyword fmt denotes string format. The format starts with the symbol % followed by numbers and letters.
x = 0.25
e. Extract or replace substrings in R
substr Syntax – substr(x, starting position, end position)
x = “abcdef”
substr(x, 1, 4)
In the above example. we are telling R to extract a string from 1st letter through the 4th letter.
Replace Substring – substr(x, starting position, end position) = Value
substr(x, 1, 3) = “11”
In the above example, we are telling R to replace first 3letters with 111.
f. String Length
The nchar function is being used to compute the length of a character value.
x = “I love Dancing”
It returns 14 as the vector ‘x’ contains 14 letters (including 2 spaces).
g. Extract word from a programming
Suppose you need to pull a first or last word from a character string.
Word Function Syntax (Library : stringr)
word(string, position of word to extract, separator)
x = “I love Dancing”
word(x, 1,sep = ” “)
In the example above, ‘1’ denotes the first word to be extracted from a string. sep=” ” denotes a single space as a delimiter (It’s the default delimiter in the word function)
Extract Last Word
x = “I love Dancing”
word(x, -1,sep = ” “)
In the example above, ‘-1’ denotes the first word but started to be reading from the right of the string. sep=” ” denotes a single space as a delimiter (It’s the default delimiter in the word function)
h. Convert Character to Uppercase / Lowercase /Propercase
In many times, we need to change the case of a word.
For example: convert the case to uppercase or lowercase.
x = “I love Dancing”
Output: “i love dancing”
The tolower() function converts letters in a string to lowercase.
Output: “I LOVE DANCING”
The toupper() function converts letters in a string to uppercase.
Output: “I Love Dancing”
The str_to_title() function converts the first letter in a string to uppercase and the remaining letters to lowercase.
i. Converting Multiple Spaces to a Single Space
It’s a challenging task to remove many spaces from a string and keep only a single space. In R, it is possible to do it with a qdap package.
x= “ritika joshi”
Output: ritika joshi
j. Repeat the character N times
We can use strrep base R function to repeat the character N times.
k. Find String in a Character Variable
The str_detect() function helps to check whether a substring exists in a string. It is equal to ‘contain’ function of SAS. It returns TRUE/FALSE against each value.
x = c(“Ritika Joshi”, “Ritika Gupta”, “Linkedin”, “Google”)
Output: TRUE TRUE FALSE FALSE
l. Splitting a Character Vector
In case of text mining. it is being required to split a string to calculate the used keywords in the list. We use ‘strsplit()’ in base R to perform this operation.
x = c(“I love Dancing”)
strsplit(x, ” “)
Output: “I” “love” “Dancing”
So, this was all in R Numeric and Character Functions. Hope you like our explanation.
Hence, we have studied in deep about various numeric and character functions in R and we have also learned different properties of R Numeric and Character functions which helps a lot in R programming.
Still, if any doubt regarding Numeric and Character Functions, ask in the comment tab.
Refer Best R Books to master R for Data Science.