Copyright © 2022-2025 aizws.net · 网站版本: v1.2.6·内部版本: v1.25.2·
页面加载耗时 0.00 毫秒·物理内存 116.8MB ·虚拟内存 1372.4MB
欢迎来到 AI 中文社区(简称 AI 中文社),这里是学习交流 AI 人工智能技术的中文社区。 为了更好的体验,本站推荐使用 Chrome 浏览器。
R 语言字符串可以使用一对单引号 ' ' 或一对双引号 " " 来表示。
以下范例演示来字符串的使用:
a <- '使用单引号' print(a) b <- "使用双引号" print(b) c <- "双引号字符串中可以包含单引号(') " print(c) d <- '单引号字符串中可以包含双引号(") ' print(d)
执行以上代码输出结果为:
[1] "使用单引号" [1] "使用双引号" [1] "双引号字符串中可以包含单引号(') " [1] "单引号字符串中可以包含双引号(\") "
以下我们来看下 R 语言一些内置函数对字符串对操作。
paste() 函数用于使用指定对分隔符来对字符串进行连接,默认对分隔符为空格。
语法格式:
paste(..., sep = " ", collapse = NULL)
参数说明:
a <- "Google" b <- 'Aizws' c <- "Taobao" print(paste(a,b,c)) print(paste(a,b,c, sep = "-")) print(paste(letters[1:6],1:6, sep = "", collapse = "=")) paste(letters[1:6],1:6, collapse = ".")
执行以上代码输出结果为:
[1] "Google Aizws Taobao" [1] "Google-Aizws-Taobao" [1] "a1=b2=c3=d4=e5=f6" [1] "a 1.b 2.c 3.d 4.e 5.f 6"
format() 函数用于格式化字符串,format() 可作用于字符串或数字。
语法格式:
format(x, digits, nsmall, scientific, width, justify = c("left", "right", "centre", "none"))
参数说明:
# 显示 9 位,最后一位四舍五入
result <- format(23.123456789, digits = 9)
print(result)
# 使用科学计数法显示
result <- format(c(6, 13.14521), scientific = TRUE)
print(result)
# 小数点右边最小显示 5 位,没有的以 0 补充
result <- format(23.47, nsmall = 5)
print(result)
# 将数字转为字符串
result <- format(6)
print(result)
# 宽度为 6 位,不够的在开头添加空格
result <- format(13.7, width = 6)
print(result)
# 左对齐字符串
result <- format("Aizws", width = 11, justify = "l")
print(result)
# 居中显示
result <- format("Aizws", width = 11, justify = "c")
print(result)
执行以上代码输出结果为:
[1] "23.1234568" [1] "6.000000e+00" "1.314521e+01" [1] "23.47000" [1] "6" [1] " 13.7" [1] "Aizws " [1] " Aizws "
nchar() 函数用于计数字符串或数字列表的长度。
语法格式:
nchar(x)
参数说明:
result <- nchar("Google Aizws Taobao")
print(result)
执行以上代码输出结果为:
[1] 23
toupper() & tolower() 函数用于将字符串的字母转化为大写或者小写。
语法格式:
toupper(x) tolower(x)
参数说明:
# 转大写
result <- toupper("Aizws")
print(result)
# 转小写
result <- tolower("Aizws")
print(result)
执行以上代码输出结果为:
[1] "CODEBAOKU" [1] "aizws"
substring() 函数用于截取字符串。
语法格式:
substring(x,first,last)
参数说明:
# 从第 2 位截取到第 5 位
result <- substring("Aizws", 2, 5)
print(result)
执行以上代码输出结果为:
[1] "odeb"