服务热线
178 0020 3020
R语言中字符串可以由双引号或者单引号包裹。
my_string1 <- "hello world" my_string2 <- 'hello world'
在双引号字符串内可以包含单引号,但是不能包含双引号,如下:
#下面语句是正确的 my_string1 <- "hello 'R' world" #下面语句是错误的 my_string2 <- "hello "R" world"
同理,单引号中间可以出现双引号,但是不能出现单引号。
字符串有很多自己的操作,下面介绍一些常用的操作。
1 paste() 字符串连接函数
paste(string1,string2,string3...., sep = " ", collapse = NULL)
string1,string2,string3...代表可以添加任意多的字符串;
seq代表连接两个字符串之间的分隔符;
collapse代表去除两个字符串之间的空格,它不会消除字符串内部的空格;
a <- "Hello" b <- 'How' c <- "are you? " print(paste(a,b,c)) print(paste(a,b,c, sep = "-")) print(paste(a,b,c, sep = "", collapse = ""))
以上代码得到如下的结果:
[1] "Hello How are you? " [1] "Hello-How-are you? " [1] "HelloHoware you? "
2 format() 格式化字符串函数
format(x, digits, nsmall, scientific, width, justify = c("left", "right", "centre", "none"))
x是向量输入。
digits是显示的总位数。
nsmall是小数点右边的最小位数。
scientific科学设置为TRUE以显示科学记数法。
width指示通过在开始处填充空白来显示的最小宽度。
justify是字符串向左,右或中心的显示。
# Total number of digits displayed. Last digit rounded off. result <- format(23.123456789, digits = 9) print(result) # Display numbers in scientific notation. result <- format(c(6, 13.14521), scientific = TRUE) print(result) # The minimum number of digits to the right of the decimal point. result <- format(23.47, nsmall = 5) print(result) # Format treats everything as a string. result <- format(6) print(result) # Numbers are padded with blank in the beginning for width. result <- format(13.7, width = 6) print(result) # Left justify strings. result <- format("Hello", width = 8, justify = "l") print(result) # Justfy string with center. result <- format("Hello", width = 8, justify = "c") print(result)
上面的代码将会输出如下的结果:
[1] "23.1234568" [1] "6.000000e+00" "1.314521e+01" [1] "23.47000" [1] "6" [1] " 13.7" [1] "Hello " [1] " Hello "
注意上面输出里面的空格。
3. nchar() 计算字符串字符个数的函数
my_string="hello world" print(nchar(my_string))
将输出11,注意包括字符串中的空格。同时可以对向量中多个元素进行统计,如下面的例子:
my_string=c("hello world","how are you") print(nchar(my_string)) [1] 11 11
4. substring() 截取字符串函数
substring(x,start,end)
x为要截取的字符向量,start为开始位置,end为结束位置
my_string="helloworld" substring(my_string,1,4)
将输出:hell。 注意:这个位置和其他一些语言中的位置不一样,其他语言中位置是从0开始的,而R语言是从1开始的。
5. toupper()和tolower()函数。
这两个函数分别将字符串变为大写,或者变为小写。
附件