《R数据科学》|| 10-14章 stringr+forcats字符串处理;functions函数

《R数据科学》|| 10-14章 stringr+forcats字符串处理;functions函数_第1张图片
r4ds

写论文的间隙换换脑子继续学习R4ds这本书。

  1. 英文原版在线https://r4ds.had.co.nz/index.html
  2. 中文翻译版已有售,建议纸质版书籍随时翻翻。电子版网盘分享 https://pan.baidu.com/s/1fkpqYahQHPkwx66XD2gGGg 提取码: akct
  3. 最近才公布的课后习题参考答案https://jrnold.github.io/r4ds-exercise-solutions/
  4. Rstudio的一些便捷CheetSheetshttps://www.rstudio.com/resources/cheatsheets/
  5. 另外在写代码过程中Rstudio操作时的方便快捷键:赋值<- Alt+“减号” ;管道符%>% Ctrl+Shift+M

十章 使用stringr处理字符串。

字符串通常包含的是非结构化或者半结构化的数据。

10.1 字符串基础

R基础函数中含有一些字符串处理函数,但方法不一致,不便于记忆。推荐使用stringr函数。函数是以str_开头

  1. 字符串的长度str_length()
  2. 字符串的组合str_c("x","y",sep = "_")
    • 向量化函数,自动循环短向量,使得其与最长的向量具有相同的长度
    • x <- c("abc", NA) ; str_c("1_",str_replace_na(x),"_1")
  3. 字符串character取子集:str_sub(x, start, end)如果是一个向量,则对向量中的每个字符串操作,截取子集
    • 对向量x<- c("Apple","Banana", "Pear")中的每个字符串 第一个字母 小写化。str_sub(x,1,1) <- str_to_lower(str_sub(x,1,1))
  4. 文本转化为大小写:全部大写str_to_upper(), 首字母大写str_to_title()
## 10.2 字符串基础
str_length(c("a","aaaaa",NA)) ## str_length 返回字符串中的字符数量
str_c("x","y","z",sep = " ")
str_c("aaa",str_replace_na(c("bbb",NA)),"ccc")

x <- c("Apple","Banana","Pear")
(str_sub(x,1,1) <- str_to_lower(str_sub(x,1,1)))## 对首字母改为小写。
x

10.2 正则匹配

利用str_view()学习正则匹配,需安装library(htmltools), htmlwidgets。R中的正则表达式大多数规则是与其它语言共通的,特殊的,\d, \s , \w

  1. str_view(x, "abc")
  2. 锚点:^ $; 单词边界:\b,如匹配一个单词 \bsum\b
  3. 特殊匹配符号:\\d, \\s, \\w, [abc], [^abc]不匹配a/b/c
  4. 数量:? + * {n,m} (..)\\1
## 10.3正则表达式进行模式匹配。
str_view(x,".a")
str_view(x,"^a")

str_view(words,"^.{7,}$",match = T) ## exercise 只显示7个字母及以上的单词
10.3 各类匹配操作
  1. 匹配检测:返回逻辑值str_detect(x, "e$")
    • 利用sum(), mean()简单统计匹配的个数。
    • 逻辑取子集方法筛选:words[str_detect(words,"x$")]
    • 与dplyr使用的另一种技巧df %>% filter(str_detect(words,"ab"))
    • 等同于str_subset(words,"x$")
    • str_count(words, "[aeiou]") 返回字符串中匹配的数量。
    • 与dplyr一起使用:df %>% mutate( vowels=str_count(w,"[aeiou]"))
  1. 提取匹配的内容:str_extract() 只提取第一个匹配的内容。
    • str_extract_all(words,color_match)返回一个列表,包含所有匹配的内容。
    • str_extract_all(words,color_match, simplify= TRUE) 返回的是一个矩阵。
    • 可先利用str_subset()找到包含匹配的chr,再用str_extract() 找到包含的匹配。
    • 利用tidyr里的extract()提取
  2. 替换匹配的内容 str_replace(words, "match_x", "replace_x")
    • 同时替换多个匹配的内容:str_replace_all()
    • 同时执行多个替换:str_replace_all(words,c("1"="one","2"="two","3"="three"))
  3. 拆分 split(sentences," ")返回的是一个列表
    • "a|b|c|d" %>% str_split("\\|") %>% .[[1]]
    • 内置的单词边界函数boundary(),会自动识别单词外的字符str_split(x, boundary("word"))
  4. 定位:str_locate
    • 使用str_locate()找出匹配的模式,再用str_sub()提取或修改匹配的内容。
## 10.4.1匹配检测
df <- tibble(w=words,i=seq_along(words))
df %>% filter(str_detect(w,"ab")) ##对于tibble表中筛选。
str_subset(words,"^y")

mean(str_count(words,"[aeiou]")) ## 每个单词中元音字母的数量
df %>% mutate(vowels=str_count(w,"[aeiou]"),consonants=str_count(w,"[^aeiou]")) ## 与mutate一起使用,加一列匹配到元音字母与非元音字母的数

####exercises
str_subset(words,"x$|^y")
words[str_detect(words,"x$|^y")]


## 10.4.3 提取匹配内容
colors <- c("red","orange","yellow","green","blue","purple")
(color_match <- str_c(colors,collapse = "|"))
has_color <- str_subset(sentences,color_match) ## 提取包含匹配的整个句子
matches <- str_extract(has_color,color_match) ##匹配包含匹配句子 的 第一个匹配内容。
str(matches)
###exercises
str_extract(sentences,"^\\S+")
str_extract_all(sentences,"\\w+s")

words_ing <- str_subset(sentences,"\\b\\w+ing\\b")
str_extract_all(words_ing,"\\b\\w+ing\\b")
## 10.4.5 分组匹配
noun <- "(a|the) (\\S+)"
has_noun <- sentences %>% str_subset(noun)
has_noun %>% str_extract(noun) 

sentences %>% str_subset(noun) %>% str_extract(noun)
str_match(has_noun,noun) ## 可以给出每个独立的分组,返回的是一个矩阵。
tibble(sentence=sentences) %>% extract(col = sentence,into = c("article","noun"),regex = "(a|the) (\\w+)",remove = F)

## 10.4.7 替换
str_replace()
str_replace_all(words,c("1"="one","2"="two","3"="three"))


## 10.4.9拆分
"a|b|c|d" %>% str_split("\\|") %>% .[[1]]
x <- "This is a sentence"
str_view_all(x,boundary("word"))  ## 返回句子中的所有单词

apropos("str")

10.5 其它类型的匹配

对于一个匹配的"pattern"来说,其完整的写法是regex("pattern")。而regex()函数中包含其它的参数

  • ignore_case=T忽略匹配的大小写
  • multiline=T 可以跨行匹配
  • comments = T 可以添加注释信息
  • dotall=T可以匹配所有字符

其它应用:当想不起函数名称时可以apropos("pattern")

十一章 使用forcats处理因子

因子在R中用于处理分类变量。分类变量是在固定的已知集合中取值的变量。

使用因子时,最常用的两种操作时修改水平的顺序和水平的值。

  • factor(x1,levels=c("a","b","c"))
  • fct_reorder() ## 重新对factor的层级进行确定。
  • 利用gss_cat数据集,其中一个问题待解决“美国民主党/共和党/中间派的人数比例是如何随时间而变化的”

十四章 函数(Functions)

当一段代码需要多次使用的时候就可以写函数来实现。先编写工作代码,而后再转换成函数的代码。包括名称/参数/主体代码

library(tidyverse)
df <- tibble(a=rnorm(10),
             b=rnorm(10),
             c=rnorm(10),
             d=rnorm(10)
)
x <- df$a
rng <- range(x,na.rm = T) ## range函数返回(最大值和最小值)
(x-rng[1])/(rng[2]-rng[1])

#### 具体函数
rescale01 <- function(x){
  rng <- range(x,na.rm = T,finite=T)
  (x-rng[1])/(rng[2]-rng[1])
} ###函数名称为rescale01
rescale01(c(df$a,Inf))
#### exercises
#1, parameters
rescale01_v2 <- function(x,na.rm_TorF,finite_TorF){
  rng <- range(x,na.rm = na.rm,finite=finite)
  (x-rng[1])/(rng[2]-rng[1])
}

#2, reverse_Inf


  1. 命名的规则:函数名一般为动词,参数为名词。使用注释来解释代码。
## exercises
#1,
f1 <- function(string,prefix){
  substr(string,1,nchar(prefix))==prefix
}
f3 <- function(x,y){
  rep(y,length.out(x))
}
  1. 条件执行(condition execution):if..else..语句
  • if..else语句中使用逻辑表达式:&& ,||
  • 向量化操作符: &,| 只可以用于多个值。

## exercise2欢迎函数
greet <- function(time=lubridate::now()){
  hr <- lubridate::hour(time)
  if(hr<12){
    print("Good morning!")
  }else if (hr<18) {
    print("Good afternoon")
  }else{
    print("Good evening")
  }
}

## exercise3
fizzbuzz <- function(x){
  ###限定输入的内容格式
  stopifnot(length(x)==1)
  stopifnot(is.numeric(x))
  
  if (x%%3==0 && x%%5!=0) {
    print("fizz")
  }else if (x%%5==0 && x%%3!=0) {
    print("buzz")
  }else if (x%%5==0 && x%%3==0) {
    print("fizzbuzz")
  }else{
    print(x)
  }
}

  1. 函数的参数:主要包括进行计算的数据,控制计算过程的细节,细节参数一般都有默认值
    n
## 使用近似正态分布计算均值两端的置信区间
mean_ci <- function(x,confidence=0.95){
  se <- sd(x)/sqrt(length(x))
  alpha <- 1-confidence
  mean(x)+se*qnorm(c(alpha/2,1-alpha/2))
}

你可能感兴趣的:(《R数据科学》|| 10-14章 stringr+forcats字符串处理;functions函数)