To understand the string concept and its function in R.
String :
Rules for string creation :
Concatenating two strings :
Syntax :
paste(arguments,sep=” ”,collapse=NULL)
Formatting numbers and strings :
Syntax :
fomat(x,digits,nsmall,scientific,width,justify)
x – The variable
digits – Total no.of digits to be displayed
nsmall – minimum digits to the right of the decimal point
scientific – To display the variable in scientific notation
width – to pad blanks in the beginning
justify – justification the the variable to left,right or center
Built in string functions :
substr(x,start,stop) – to get the subring of a string whose position is determined by start and stop values.
Strsplit(x,”split”) – to split the string into multiple substring when encountered with the substring given in double quotes
Toupper() – to convert the string to upper case
Tolower() – to convert the string to lower case
Sub(pattern,replacement,x) – to find a substring given in pattern and replace it with the string given in replacement from a string
Nchar(x) – to find the length of the string
Source code : string creation and concatenation
#string creation
a<-“Kaliamman kovil street”
b<-“Virugambakkam”
c<-“chennai”
#concatenating strings
d=paste(a,b,c)
cat(“The address is : “,d )
# comma (‘) as separator b/w strings
d=paste(a,b,c,sep=”,”)
cat(“\nThe address is : “,d )
#eliminating white spaces b/w strings but not within a string
d=paste(a,b,c,sep=””,collapse=””)
cat(“\nThe address is : “,d )
Source code : formatting strings and numbers
x=256.256987456321
#Total number of digits to be printed
print(format(x,digits=10))
#to fix no.of digits after the decimal point
print(format(x,nsmall=3))
#To print the vale in scientific notation
print(format(x,digits=10,nsmall=3,scientific=TRUE))
#Padding blanks in the beginning
print(format(x,nsmall=3,width=10))
#justification of the given argument
print(format(“Welcome”,width = 10,justify=”l”))
print(format(“Welcome”,width = 10,justify=”c”))
print(format(“Welcome”,width = 10,justify=”r”))
Source code : String functions
#inbuilt string functions
str1=readline(prompt=”Enter the string : “)
print(substr(str1,5,10))
#splitting the string
dt=readline(prompt=”Enter the date with / notation : “)
print(strsplit(dt,”/”))
#To upper case
cat(“Converting the string to upper case “,toupper(str1))
#to lower case
cat(“\nConverting the string to lower case”,tolower(str1))
str2=readline(prompt=”Enter the next string : “)
#replacing a substring with another substring
cat(“\nReplacing the string : “,sub(“te”,”ting”,str2),”\n”)
#to find the length of the string
print(str1)
cat(“\nThe length of the above string is “,nchar(str1))