R语言学习笔记

《R语言实战》学习笔记---Chapter5(4) 高级数据管理

2023-08-20  本文已影响0人  RSP小白之路

字符处理函数

tidyverse集合中有一个非常强大的处理字符串的包,可以看这篇文章R语言stringr包处理字符串 - 简书 (jianshu.com)。这篇文章是阅读《R语言实战》的学习笔记,我们继续书中的内容。

注意,涉及到正则表达式的部分都先忽略,先把基础的弄明白,正则表达式需要专门深入学习。

> x <- c("aghe", "1", "语言", "哈", "ahjdna")
> nchar(x)
[1] 4 1 2 1 6
> length(x)
[1] 5

可以看到,在R里,中文汉字一个字是一个字符宽度。同时注意区分和lengh函数的区别,length返回的是整个数据结构的元素数量

> y <- "122267"
> 
> substr(y, 2, 4)
[1] "222"
> 
> substr(y,2,4 ) <- "ccc"
> 
> print(y)
[1] "1ccc67"

注意,这个替换是在原字符串进行替换,且R索引从1开始。

> x <- "jakAnh"
> 
> y <- c("slA" , "djkaA")
> 
> grep("A", x, ignore.case = F, fixed = T)
[1] 1
> 
> grep("A", x, ignore.case = T, fixed = T)
[1] 1
Warning message:
In grep("A", x, ignore.case = T, fixed = T) :
  argument 'ignore.case = TRUE' will be ignored
> 
> grep("A", y, ignore.case = F, fixed = T)
[1] 1 2
> 
> grep("A", y, ignore.case = T, fixed = T)
[1] 1 2
Warning message:
In grep("A", y, ignore.case = T, fixed = T) :
  argument 'ignore.case = TRUE' will be ignored

注意,首先这个函数返回的是下标索引,所以在取数据结构子集时可以用。
再看,函数作用的数据结构是向量,即使输入一个字符串,而其中包含多个匹配上的模式,也只会返回1

使用格式sub(pattern ,replacement , x , ignore.case=FALSE,fixed=FALSE),后面两个常用设置和上一个函数一样,不多赘述。

> y <- "23777c"
> sub('7', 'M', y, ignore.case = T, fixed = T)
[1] "23M77c"
Warning message:
In sub("7", "M", y, ignore.case = T, fixed = T) :
  argument 'ignore.case = TRUE' will be ignored

注意,它只替换了匹配到的第一个字符。

> y <- "23777c"
> strsplit(y, "7", fixed = T)
[[1]]
[1] "23" ""   ""   "c" 

可以看到,是以7为分隔符,字符被分成了4个部分,其中两个为空。

> nth <- paste0(1:12, c("st", "nd", "rd", rep("th", 9)))
> 
> month.abb  # 内置数据,就和letters一样
 [1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
> paste(month.abb, "is the", nth, "month of the year.")
 [1] "Jan is the 1st month of the year."  "Feb is the 2nd month of the year." 
 [3] "Mar is the 3rd month of the year."  "Apr is the 4th month of the year." 
 [5] "May is the 5th month of the year."  "Jun is the 6th month of the year." 
 [7] "Jul is the 7th month of the year."  "Aug is the 8th month of the year." 
 [9] "Sep is the 9th month of the year."  "Oct is the 10th month of the year."
[11] "Nov is the 11th month of the year." "Dec is the 12th month of the year."
> library(stringr)
> library(Hmisc)

载入程辑包:‘Hmisc’

The following objects are masked from ‘package:dplyr’:

    src, summarize

The following objects are masked from ‘package:base’:

    format.pval, units

> 
> x <- 'apple'
> y <- 'BANANA'
> 
> toupper(x)
[1] "APPLE"
> tolower(y)
[1] "banana"
> capitalize(x)  # HMisc包函数
[1] "Apple"
> str_to_title(x) # stringr包函数
[1] "Apple"

上一篇 下一篇

猜你喜欢

热点阅读