如何从R中的字符串中提取前两个字符?

字符串可以短也可以长,在R中也可以有向量或字符串列表。当我们想将字符串用于单个或多个比较时,通常会提取部分字符串。如果要从字符串中提取前两个字符,则可以使用substr函数,语法为substr(“ String_object Or String”,start = 1,stop = 2)

例子

x1<-"Nhooo"
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"