现在位置: 首页 > R 教程 > 正文

R toupper() 和 tolower() 函数 - 大小写转换

R 语言实例 R 语言实例

R toupper() 函数用于将字符串转为大写,tolower() 转为小写。

在数据清洗和文本预处理时,统一大小写是常见的操作。

这两个函数语法格式如下:

toupper(x)
tolower(x)

参数说明:

  • x 输入字符串或字符串向量。

实例

text <- "Hello RUNOOB World"

# 转为大写
print(toupper(text))

# 转为小写
print(tolower(text))

# 向量中的大小写转换
words <- c("Apple", "Banana", "Cherry")
print("全部大写:")
print(toupper(words))
print("全部小写:")
print(tolower(words))

执行以上代码输出结果为:

[1] "HELLO RUNOOB WORLD"
[1] "hello runoob world"
[1] "全部大写:"
[1] "APPLE"  "BANANA" "CHERRY"
[1] "全部小写:"
[1] "apple"  "banana" "cherry"

大小写转换常用于数据匹配前的标准化处理:

实例

# 统一为小写后进行比较
user_input <- "RunOOb"
standard <- tolower(user_input)

if (standard == "runoob") {
  print("匹配成功!")
}

# 首字母大写(自定义函数)
capitalize <- function(x) {
  paste0(toupper(substr(x, 1, 1)),
         tolower(substr(x, 2, nchar(x))))
}
print(capitalize(c("hello", "WORLD", "rUnoob")))

执行以上代码输出结果为:

[1] "匹配成功!"
[1] "Hello"  "World"  "Runoob"

R 语言实例 R 语言实例