R String Functions

R has following basic string functions.

paste(vectors,sep,collapse): Concatenate strings. sep is a string to separate terms; collapse is optional string to separate “collapsed” results.

> k1<-"Welcome to " > k2<-"k2schools" > paste(k1,k2,sep="",collapse=NULL) [1] "Welcome to k2schools"

substr(x,start,stop): get or assign substrings in a character vector.

> k1<-"Welcome to " > substr(k1,1,7) #To extract character string from 1 to 7 [1] "Welcome"

nchar(x): To check number of characters.

> k1<-"Welcome to " > nchar(k1) #To get total number of characters [1] 11

length(x): To check the number of elements.

> a<-c("Hello World",1:5) > a [1] "Hello World" "1" "2" "3" "4" "5" > length(a) #Total number of elements [1] 6 > nchar(a) #It calculates length of each element in a. [1] 11 1 1 1 1 1

tolower(x): To convert string to lower.

> k1<-"Welcome to " > tolower(k1) [1] "welcome to "

toupper(x): To convert string to Upper.

> k1<-"Welcome to " > toupper(k1) [1] "WELCOME TO "

strtrim(x): Trim character strings to specified display widths(Truncates string)

> k [1] "Welcome to k2schools" > strtrim(k,9) [1] "Welcome t" > strtrim(k,14) [1] "Welcome to k2"

chartr(): character map replacement

> k [1] "Welcome to k2schools" > chartr('co','df',k) [1] "Weldfme tf k2sdhffls"

strsplit(x): split string into substrings at occurances of regexp.

> a<-c("Hyderabad","Elchuru","Ongole","Texas") > strsplit(a,"e") [[1]] [1] "Hyd" "rabad" [[2]] [1] "Elchuru" [[3]] [1] "Ongol" [[4]] [1] "T" "xas"

grep(pattern,x): searches for matches to pattern within x

> string = c("school", "schools", "schoolz") > grep("\\bschool\\b",string) [1] 1 > grep("\\bschools\\b",string) [1] 2 > grep("\\bschoolz\\b",string) [1] 3

sub(pattern,replacement,x): function replaces the first match of a string, if the parameter is a string vector, replaces the first match of all elements.

> k<-"Welcome to k2schools and also visit to python tutorials" > sub("to","xyz",k) #This replaces only first 'to' with 'xyz' [1] "Welcome xyz k2schools and also visit to python tutorials"

gsub(): function replaces all matches of a string.

> k<-"Welcome to k2schools and also visit to python tutorials" > gsub("to","xyz",k) #This replaces all 'to' with 'xyz' [1] "Welcome xyz k2schools and also visit xyz python tuxyzrials"

Powered by WordPress