R 简明教程
R - Strings
在 R 中用一对单引号或双引号写的任何值都被视为一个字符串。内部上,R 将每一个字符串都存储在双引号中,即使您用单引号创建它们。
Rules Applied in String Construction
-
字符串开头和结尾的引号都应该是双引号或单引号。它们不能混合使用。
-
可以将双引号插入到以单引号开始和结尾的字符串中。
-
可以将单引号插入到以双引号开始和结尾的字符串中。
-
不能将双引号插入到以双引号开始和结尾的字符串中。
-
不能将单引号插入到以单引号开始和结尾的字符串中。
Examples of Valid Strings
以下示例说明了在 R 中创建字符串的规则。
a <- 'Start and end with single quote'
print(a)
b <- "Start and end with double quotes"
print(b)
c <- "single quote ' in between double quotes"
print(c)
d <- 'Double quotes " in between single quote'
print(d)
运行以上代码时,我们将得到以下输出 −
[1] "Start and end with single quote"
[1] "Start and end with double quotes"
[1] "single quote ' in between double quote"
[1] "Double quote \" in between single quote"
String Manipulation
Syntax
paste 函数的基本语法为:
paste(..., sep = " ", collapse = NULL)
以下是所用参数的描述 -
-
…​ 表示组合的任意数量的参数。
-
sep 表示参数之间的任意分隔符。它是可选的。
-
collapse 用于消除两个字符串之间的空格。但不是一个字符串的两个单词之间的空格。
Example
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? "
Syntax
format 函数的基本语法为:
format(x, digits, nsmall, scientific, width, justify = c("left", "right", "centre", "none"))
以下是所用参数的描述 -
-
x 是向量的输入。
-
digits 是显示的数字的总数。
-
nsmall 是小数点右边最少的数字。
-
scientific 设置为 TRUE 以显示科学计数法。
-
width 表示初始填充空格显示的最少宽度。
-
justify 是将字符串显示在左、右或中间。
Example
# 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 "
Example
# Changing to Upper case.
result <- toupper("Changing To Upper")
print(result)
# Changing to lower case.
result <- tolower("Changing To Lower")
print(result)
当我们执行上述代码时,会产生以下结果 -
[1] "CHANGING TO UPPER"
[1] "changing to lower"