R 语言字符串
字符串字面量
字符或字符串用于存储文本。字符串由单引号或双引号包围:
"hello" 相当于 'hello':
实例
"hello"'hello'
将字符串赋给变量
将字符串赋给变量时,变量后跟 <- 运算符和字符串:
实例
str <- "Hello"str # print the value of str
多行字符串
可以将多行字符串指定给这样的变量:
实例
str <- "Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididuntut labore et dolore magna aliqua."str
但是,请注意,R 将在每一个换行符的末尾添加一个 "\n"。这称为转义字符,n 字符表示 新行。
如果希望换行符插入到代码中的相同位置,请使用 cat() 函数:
实例
str <- "Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididuntut labore et dolore magna aliqua."cat(str)
字符串长度
R 语言中有许多有用的字符串函数。
例如,要查找字符串中的字符数,请使用 nchar() 函数:
实例
str <- "Hello World!"nchar(str)
检查字符串
使用 grepl() 函数检查字符串中是否存在字符或字符序列:
实例
str <- "Hello World!"grepl("H", str)grepl("Hello", str)grepl("X", str)
把两个字符串连起来
使用 paste() 函数合并/连接两个字符串:
实例
str1 <- "Hello"str2 <- "World"paste(str1, str2)
转义字符
要在字符串中插入特殊字符,必须使用转义字符。
转义字符是一个反斜杠 \ 后跟要插入的字符。
下面一个例子就是被双引号包围的字符串中的 双引号:
实例
str <- "We are the so-called "Vikings", from the north."str
结果:
Error: unexpected symbol in "str <- "We are the so-called "Vikings"
要解决这样的问题,可以使用转义字符 \”:
实例
转义字符允许在通常不允许的情况下使用双引号:
str <- "We are the so-called \"Vikings\", from the north."strcat(str)
请注意,自动打印 str 变量将在输出中打印反斜杠。可以使用
cat() 函数打印它,这样就没有反斜杠了。R 语言中的其他转义字符:
| 代码 | 结果 |
|---|---|
| \ | 反斜杠 |
| \n | 新的一行 |
| \r | 回车 |
| \t | 制表定位 Tab |
| \b | 回退 |