R语言字符串相关操作
字符串操作常用函数
函数 | 作用 | 示例 | 结果 |
---|---|---|---|
toupper | 转换为大写 | toupper("abc") | “ABC” |
tolower | 转换为小写 | tolower("ABC") | “abc” |
nchar | 统计字符数量 | nchar("abc") | 3 |
substr | 截取字符串 | substr("abc",1,2) | “ab” |
substring | 截取字符串到结束 | substring("abc",2) | “bc” |
as.numeric | 将字符串转化为数字 | as.numeric("123") | 123 |
as.character | 将数字转化为字符串 | as.character(123) | “123” |
strsplit | 分隔拆分字符串 | strsplit("2022:9:21",':') | “2022” “9” “21” |
gsub | 替换字符串 | gsub(':','/',"2022:9:21") | “2022/9/21” |
字符串连接
paste(str1,str2,...,sep = ' ')
其中sep是连接符,默认为空格。
paste0(str1,str2,...,sep = '')
默认直接连接。
> paste0("asdasd","ASDASD")
[1] "asdasdASDASD"
> paste("asdasd","ASDASD",sep = '$')
[1] "asdasd$ASDASD"
> paste0(c("asdasd","ASDASD"),collapse = '')
[1] "asdasdASDASD"
格式化字符串
format(x,digits,nsmall,scientific,width,justify = c("left","right","centre","none"))
用于格式化字符串或数字。
参数说明:
- x:输入对向量
- digits:显示的位数
- nsmall:小数点右边显示的最少位数
- scientific:设置科学计数法
- width:通过开头填充空白来显示最小的宽度
- justify:设置位置,显示可以是左边、右边、中间等。
> format(123.1231234,digits=5)
[1] "123.12"
> format(123.1231234,width=10)
[1] " 123.1231"
> format("google",width=10,justify='centre')
[1] " google "