R Strings Handling
Handling Strings
substr() extracts or replaces substrings in a character vector
Syntax
str(substr)
function (x, start, stop)
Where,
x: character vector
start: integer, the first element to be replaced
stop: integer, the last element to be replaced
CODE/PROGRAM/EXAMPLE
txt
[1] "a test of capitalizing"
substr(txt, 3, 6)
[1] "test"
newTxt <- c("Red", "Green", "Blue")
substr(newTxt, 1, 1)
[1] "R" "G" "B"
txt
[1] "a test of capitalizing"
substr(txt, 3, 6) <- "type"
print(txt)
[1] "a type of capitalizing"
‘test’ has been extracted from vector ‘txt’ and replaced with ‘type’
chartr() does string substitutions
Syntax
str(chartr)
function (old, new, x)
Where,
old : old string to be substituted
new : new string
x : object with the text data
CODE/PROGRAM/EXAMPLE
newTxt
[1] "Red" "Blue" "Green"
chartr("e", "O", newTxt)
[1] "ROd" "BluO" "GrOOn"
strsplit() splits the elements of a character vector ‘x’ into substrings, according to the matches to substring split within them
Syntax
str(strsplit)
function (x, split, fixed = FALSE, perl = FALSE, useBytes = FALSE)
Where,
x: the object with the text data
split: the position at which the data has to be split
rest are additional options for more detailed search
txt1 <- c(“.count”, “..finan.ce”, “cost”, “.date”, “..coin”)
strsplit(txt1, “o”)
Output: