字符串向量可以包含任何值,包括空格。有时,也会读取带有一些空格的字符串向量,而我们想分割向量然后提取一些值。例如,如果一个字符串具有“ ABC 123”,那么我们可能要提取数字123,以便我们可以在分析中使用它。如果字符串向量具有相等大小的字符串,则可以在substr函数的帮助下轻松完成此操作。
> x1<-c("1 00","1 01","1 02","1 03","1 03","1 04") > x1 [1] "1 00" "1 01" "1 02" "1 03" "1 03" "1 04" > Numeric_Last_two_x1<-substr(x1,start=4,stop=5) > Numeric_Last_two_x1 [1] "00" "01" "02" "03" "03" "04" > Numeric_Last_first_x1<-substr(x1,start=4,stop=4) > Numeric_Last_first_x1 [1] "0" "0" "0" "0" "0" "0" > Numeric_Last_last_x1<-substr(x1,start=5,stop=5) > Numeric_Last_last_x1 [1] "0" "1" "2" "3" "3" "4" > x2<-c("1 0","1 1","1 2","1 3","1 4","1 5") > x2 [1] "1 0" "1 1" "1 2" "1 3" "1 4" "1 5" > Last_value_x2<-substr(x2,start=4,stop=4) > Last_value_x2 [1] "0" "1" "2" "3" "4" "5" > First_value_x2<-substr(x2,start=1,stop=1) > First_value_x2 [1] "1" "1" "1" "1" "1" "1" > x3<-c("A 0","B 1","C 2","D 3","E 4","F 5") > x3 [1] "A 0" "B 1" "C 2" "D 3" "E 4" "F 5" > Last_value_x3<-substr(x3,start=4,stop=4) > Last_value_x3 [1] "0" "1" "2" "3" "4" "5" > x4<-c("A 1151","B 1152","C 1153","D 1154","E 1155","F 1156") > x4 [1] "A 1151" "B 1152" "C 1153" "D 1154" "E 1155" "F 1156" > Last_value_x4<-substr(x4,start=7,stop=7) > Last_value_x4 [1] "1" "2" "3" "4" "5" "6" > Last_three_value_x4<-substr(x4,start=5,stop=7) > Last_three_value_x4 [1] "151" "152" "153" "154" "155" "156" > Last_two_value_x4<-substr(x4,start=6,stop=7) > Last_two_value_x4 [1] "51" "52" "53" "54" "55" "56" > Last_numeric_value_x4<-substr(x4,start=4,stop=7) > Last_numeric_value_x4 [1] "1151" "1152" "1153" "1154" "1155" "1156" > x5<-c("System-1 191","System-2 352","System-3 498","System-4 154","System-5 327","System-6 456") > x5 [1] "System-1 191" "System-2 352" "System-3 498" "System-4 154" [5] "System-5 327" "System-6 456" > Last_numeric_value_x5<-substr(x5,start=11,stop=13) > Last_numeric_value_x5 [1] "191" "352" "498" "154" "327" "456" > Last_digit_x5<-substr(x5,start=13,stop=13) > Last_digit_x5 [1] "1" "2" "8" "4" "7" "6" > Last_two_digits_x5<-substr(x5,start=12,stop=13) > Last_two_digits_x5 [1] "91" "52" "98" "54" "27" "56" > Digits_in_System_x5<-substr(x5,start=8,stop=8) > Digits_in_System_x5 [1] "1" "2" "3" "4" "5" "6"