R trimws() 函数 - 去除空白字符
R trimws() 函数用于去除字符串首尾的空白字符(空格、制表符、换行符等)。
在数据清洗中,trimws() 可以去除用户输入中不小心带上的多余空格。
trimws() 函数语法格式如下:
trimws(x, which = c("both", "left", "right"))
参数说明:
x 输入字符串向量。
which 去除哪一侧的空白:"both"(两侧)、"left"(左侧)、"right"(右侧)。
实例
text <- " Hello RUNOOB "
# 去除两侧空白
result1 <- trimws(text)
print(result1)
# 只去除左侧空白
result2 <- trimws(text, which = "left")
print("只去左侧:")
print(result2)
# 只去除右侧空白
result3 <- trimws(text, which = "right")
print("只去右侧:")
print(result3)
# 处理向量
names_with_spaces <- c(" 张三 ", " 李四", "王五 ")
cleaned_names <- trimws(names_with_spaces)
print("清理后的名字:")
print(cleaned_names)
# 去除两侧空白
result1 <- trimws(text)
print(result1)
# 只去除左侧空白
result2 <- trimws(text, which = "left")
print("只去左侧:")
print(result2)
# 只去除右侧空白
result3 <- trimws(text, which = "right")
print("只去右侧:")
print(result3)
# 处理向量
names_with_spaces <- c(" 张三 ", " 李四", "王五 ")
cleaned_names <- trimws(names_with_spaces)
print("清理后的名字:")
print(cleaned_names)
执行以上代码输出结果为:
[1] "Hello RUNOOB" [1] "只去左侧:" [1] "Hello RUNOOB " [1] "只去右侧:" [1] " Hello RUNOOB" [1] "清理后的名字:" [1] "张三" "李四" "王五"

R 语言实例