How to extract first two characters from a string in R?

R ProgrammingServer Side ProgrammingProgramming

A string can be short or long, also we can have a vector or list of strings as well in R. Extraction of partial string is common when we want to use the strings for single or multiple comparisons. If we want to extract first two characters from a string, we can use substr function and the syntax is substr(“String_object Or String”,start=1,stop=2)

Examples

x1<-"Tutorialspoint"
substr(x1,start=1,stop=2)
[1] "Tu"
x2<-"Programing"
substr(x2,start=1,stop=2)
[1] "Pr"
x3<-"R-Programming"
substr(x3,start=1,stop=2)
[1] "R-"
x4<-"R<>Programming"
substr(x4,start=1,stop=2)
[1] "R<"
x5<-"R!Programming"
substr(x5,start=1,stop=2)
[1] "R!"
x6<-"R/Programming"
substr(x6,start=1,stop=2)
[1] "R/"
x7<-"R@Programming"
substr(x7,start=1,stop=2)
[1] "R@"
x8<-"R~Programming"
substr(x8,start=1,stop=2)
[1] "R~"
x9<-"VALANY"
substr(x9,start=1,stop=2)
[1] "VA"
x10<-"1 to 10"
substr(x10,start=1,stop=2)
[1] "1 "
x11<-"10 to 20"
substr(x11,start=1,stop=2)
[1] "10"
x12<-"North to South"
substr(x12,start=1,stop=2)
[1] "No"
x13<-"No to Yes"
substr(x13,start=1,stop=2)
[1] "No"
x14<-"1.5 and 2.5"
substr(x14,start=1,stop=2)
[1] "1."
x15<-c("AB","CD","EF","GH","IJ")
substr(x15,start=1,stop=2)
[1] "AB" "CD" "EF" "GH" "IJ"
x16<-c("ABCD","EFGH","IJKL")
substr(x16,start=1,stop=2)
[1] "AB" "EF" "IJ"
raja
Published on 24-Aug-2020 13:02:13
Advertisements