r4ds
寫論文的間隙換換腦子繼續學習R4ds這本書。
- 英文原版在線https://r4ds.had.co.nz/index.html
- 中文翻譯版已有售,建議紙質版書籍隨時翻翻。電子版網盤分享 https://pan.baidu.com/s/1fkpqYahQHPkwx66XD2gGGg 提取碼: akct
- 最近才公布的課后習題參考答案https://jrnold.github.io/r4ds-exercise-solutions/
- Rstudio的一些便捷CheetSheetshttps://www.rstudio.com/resources/cheatsheets/
- 另外在寫代碼過程中Rstudio操作時的方便快捷鍵:賦值<-
Alt+“減號”
;管道符%>%Ctrl+Shift+M
十章 使用stringr處理字符串。
字符串通常包含的是非結構化或者半結構化的數據。
10.1 字符串基礎
R基礎函數中含有一些字符串處理函數,但方法不一致,不便于記憶。推薦使用stringr函數。函數是以str_開頭
- 字符串的長度
str_length()
- 字符串的組合
str_c("x","y",sep = "_")
- 向量化函數,自動循環短向量,使得其與最長的向量具有相同的長度
- x <- c("abc", NA) ; str_c("1_",str_replace_na(x),"_1")
- 字符串character取子集:
str_sub(x, start, end)
。如果是一個向量,則對向量中的每個字符串操作,截取子集- 對向量x<- c("Apple","Banana", "Pear")中的每個字符串 第一個字母 小寫化。
str_sub(x,1,1) <- str_to_lower(str_sub(x,1,1))
- 對向量x<- c("Apple","Banana", "Pear")中的每個字符串 第一個字母 小寫化。
- 文本轉化為大小寫:全部大寫
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
- str_view(x, "abc")
- 錨點:^ $; 單詞邊界:
\b
,如匹配一個單詞\bsum\b
- 特殊匹配符號:\\d, \\s, \\w, [abc], [^abc]不匹配a/b/c。
- 數量:? + * {n,m} (..)\\1
## 10.3正則表達式進行模式匹配。
str_view(x,".a")
str_view(x,"^a")
str_view(words,"^.{7,}$",match = T) ## exercise 只顯示7個字母及以上的單詞
10.3 各類匹配操作
- 匹配檢測:返回邏輯值
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]"))
- 提取匹配的內容:
str_extract()
只提取第一個匹配的內容。-
str_extract_all(words,color_match)
返回一個列表,包含所有匹配的內容。 -
str_extract_all(words,color_match, simplify= TRUE)
返回的是一個矩陣。 - 可先利用str_subset()找到包含匹配的chr,再用str_extract() 找到包含的匹配。
- 利用tidyr里的extract()提取
-
- 替換匹配的內容
str_replace(words, "match_x", "replace_x")
- 同時替換多個匹配的內容:
str_replace_all()
- 同時執行多個替換:
str_replace_all(words,c("1"="one","2"="two","3"="three"))
- 同時替換多個匹配的內容:
- 拆分
split(sentences," ")
返回的是一個列表"a|b|c|d" %>% str_split("\\|") %>% .[[1]]
- 內置的單詞邊界函數boundary(),會自動識別單詞外的字符
str_split(x, boundary("word"))
- 定位:
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
- 命名的規則:函數名一般為動詞,參數為名詞。使用注釋來解釋代碼。
## exercises
#1,
f1 <- function(string,prefix){
substr(string,1,nchar(prefix))==prefix
}
f3 <- function(x,y){
rep(y,length.out(x))
}
- 條件執行(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)
}
}
- 函數的參數:主要包括進行計算的數據,控制計算過程的細節,細節參數一般都有默認值
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))
}