R 字符串

字符串字面量

一个字符或字符串用于存储文本。 字符串用单引号或双引号括起来:

"hello"'hello' 相同:

实例

"hello"
'hello'
亲自试一试 »

将字符串分配给变量

将字符串分配给变量是通过变量后跟 <- 运算符和字符串:

实例

str <- "Hello"
str # 打印 str 的值
亲自试一试 »

多行字符串

您可以像这样将多行字符串分配给变量:

实例

str <- "Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."

str # 打印 str 的值
亲自试一试 »

但是,请注意 R 将在每个换行符的末尾添加一个"\n"。 这称为转义字符,n 字符表示换行

如果要在代码中的相同位置插入换行符,请使用 cat() 函数:

实例

str <- "Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut 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."

str
cat(str)
亲自试一试 »

请注意,自动打印 str 变量将在输出中打印反斜杠。 您可以使用 cat() 函数来打印它而不使用反斜杠。

R 中的其他转义字符:

代码 结果
\\ 反斜杠
\n 换行
\r 回车
\t Tab
\b 退格