r4ds
寫論文的間隙換換腦子繼續(xù)學(xué)習(xí)R4ds這本書。
- 英文原版在線https://r4ds.had.co.nz/index.html
- 中文翻譯版已有售晦溪,建議紙質(zhì)版書籍隨時(shí)翻翻瀑粥。電子版網(wǎng)盤分享 https://pan.baidu.com/s/1fkpqYahQHPkwx66XD2gGGg 提取碼: akct
- 最近才公布的課后習(xí)題參考答案https://jrnold.github.io/r4ds-exercise-solutions/
- Rstudio的一些便捷CheetSheetshttps://www.rstudio.com/resources/cheatsheets/
- 另外在寫代碼過程中Rstudio操作時(shí)的方便快捷鍵:賦值<-
Alt+“減號(hào)”
;管道符%>%Ctrl+Shift+M
十章 使用stringr處理字符串三圆。
字符串通常包含的是非結(jié)構(gòu)化或者半結(jié)構(gòu)化的數(shù)據(jù)狞换。
10.1 字符串基礎(chǔ)
R基礎(chǔ)函數(shù)中含有一些字符串處理函數(shù),但方法不一致舟肉,不便于記憶修噪。推薦使用stringr函數(shù)。函數(shù)是以str_開頭
- 字符串的長度
str_length()
- 字符串的組合
str_c("x","y",sep = "_")
- 向量化函數(shù)路媚,自動(dòng)循環(huán)短向量黄琼,使得其與最長的向量具有相同的長度
- x <- c("abc", NA) ; str_c("1_",str_replace_na(x),"_1")
- 字符串character取子集:
str_sub(x, start, end)
。如果是一個(gè)向量整慎,則對(duì)向量中的每個(gè)字符串操作脏款,截取子集- 對(duì)向量x<- c("Apple","Banana", "Pear")中的每個(gè)字符串 第一個(gè)字母 小寫化。
str_sub(x,1,1) <- str_to_lower(str_sub(x,1,1))
- 對(duì)向量x<- c("Apple","Banana", "Pear")中的每個(gè)字符串 第一個(gè)字母 小寫化。
- 文本轉(zhuǎn)化為大小寫:全部大寫
str_to_upper()
, 首字母大寫str_to_title()
## 10.2 字符串基礎(chǔ)
str_length(c("a","aaaaa",NA)) ## str_length 返回字符串中的字符數(shù)量
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)))## 對(duì)首字母改為小寫裤园。
x
10.2 正則匹配
利用str_view()學(xué)習(xí)正則匹配撤师,需安裝library(htmltools), htmlwidgets。R中的正則表達(dá)式大多數(shù)規(guī)則是與其它語言共通的拧揽,特殊的剃盾,\d, \s , \w
- str_view(x, "abc")
- 錨點(diǎn):^ $; 單詞邊界:
\b
,如匹配一個(gè)單詞\bsum\b
- 特殊匹配符號(hào):\\d, \\s, \\w, [abc], [^abc]不匹配a/b/c。
- 數(shù)量:? + * {n,m} (..)\\1
## 10.3正則表達(dá)式進(jìn)行模式匹配强法。
str_view(x,".a")
str_view(x,"^a")
str_view(words,"^.{7,}$",match = T) ## exercise 只顯示7個(gè)字母及以上的單詞
10.3 各類匹配操作
- 匹配檢測:返回邏輯值
str_detect(x, "e$")
- 利用sum(), mean()簡單統(tǒng)計(jì)匹配的個(gè)數(shù)万俗。
- 邏輯取子集方法篩選:words[str_detect(words,"x$")]
-
與dplyr使用的另一種技巧 :
df %>% filter(str_detect(words,"ab"))
- 等同于
str_subset(words,"x$")
-
str_count(words, "[aeiou]")
返回字符串中匹配的數(shù)量。 - 與dplyr一起使用:
df %>% mutate( vowels=str_count(w,"[aeiou]"))
- 提取匹配的內(nèi)容:
str_extract()
只提取第一個(gè)匹配的內(nèi)容饮怯。-
str_extract_all(words,color_match)
返回一個(gè)列表闰歪,包含所有匹配的內(nèi)容。 -
str_extract_all(words,color_match, simplify= TRUE)
返回的是一個(gè)矩陣蓖墅。 - 可先利用str_subset()找到包含匹配的chr库倘,再用str_extract() 找到包含的匹配。
- 利用tidyr里的extract()提取
-
- 替換匹配的內(nèi)容
str_replace(words, "match_x", "replace_x")
- 同時(shí)替換多個(gè)匹配的內(nèi)容:
str_replace_all()
- 同時(shí)執(zhí)行多個(gè)替換:
str_replace_all(words,c("1"="one","2"="two","3"="three"))
- 同時(shí)替換多個(gè)匹配的內(nèi)容:
- 拆分
split(sentences," ")
返回的是一個(gè)列表"a|b|c|d" %>% str_split("\\|") %>% .[[1]]
- 內(nèi)置的單詞邊界函數(shù)boundary()论矾,會(huì)自動(dòng)識(shí)別單詞外的字符
str_split(x, boundary("word"))
- 定位:
str_locate
- 使用str_locate()找出匹配的模式教翩,再用str_sub()提取或修改匹配的內(nèi)容。
## 10.4.1匹配檢測
df <- tibble(w=words,i=seq_along(words))
df %>% filter(str_detect(w,"ab")) ##對(duì)于tibble表中篩選贪壳。
str_subset(words,"^y")
mean(str_count(words,"[aeiou]")) ## 每個(gè)單詞中元音字母的數(shù)量
df %>% mutate(vowels=str_count(w,"[aeiou]"),consonants=str_count(w,"[^aeiou]")) ## 與mutate一起使用饱亿,加一列匹配到元音字母與非元音字母的數(shù)
####exercises
str_subset(words,"x$|^y")
words[str_detect(words,"x$|^y")]
## 10.4.3 提取匹配內(nèi)容
colors <- c("red","orange","yellow","green","blue","purple")
(color_match <- str_c(colors,collapse = "|"))
has_color <- str_subset(sentences,color_match) ## 提取包含匹配的整個(gè)句子
matches <- str_extract(has_color,color_match) ##匹配包含匹配句子 的 第一個(gè)匹配內(nèi)容。
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) ## 可以給出每個(gè)獨(dú)立的分組,返回的是一個(gè)矩陣彪笼。
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 其它類型的匹配
對(duì)于一個(gè)匹配的"pattern"來說钻注,其完整的寫法是regex("pattern")。而regex()函數(shù)中包含其它的參數(shù)
-
ignore_case=T
忽略匹配的大小寫 -
multiline=T
可以跨行匹配 -
comments = T
可以添加注釋信息 -
dotall=T
可以匹配所有字符
其它應(yīng)用:當(dāng)想不起函數(shù)名稱時(shí)可以apropos("pattern")
十一章 使用forcats處理因子
因子在R中用于處理分類變量配猫。分類變量是在固定的已知集合中取值的變量幅恋。
使用因子時(shí),最常用的兩種操作時(shí)修改水平的順序和水平的值泵肄。
- factor(x1,levels=c("a","b","c"))
- fct_reorder() ## 重新對(duì)factor的層級(jí)進(jìn)行確定捆交。
- 利用gss_cat數(shù)據(jù)集,其中一個(gè)問題待解決“美國民主黨/共和黨/中間派的人數(shù)比例是如何隨時(shí)間而變化的”
十四章 函數(shù)(Functions)
當(dāng)一段代碼需要多次使用的時(shí)候就可以寫函數(shù)來實(shí)現(xiàn)腐巢。先編寫工作代碼品追,而后再轉(zhuǎn)換成函數(shù)的代碼。包括名稱/參數(shù)/主體代碼
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函數(shù)返回(最大值和最小值)
(x-rng[1])/(rng[2]-rng[1])
#### 具體函數(shù)
rescale01 <- function(x){
rng <- range(x,na.rm = T,finite=T)
(x-rng[1])/(rng[2]-rng[1])
} ###函數(shù)名稱為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
- 命名的規(guī)則:函數(shù)名一般為動(dòng)詞冯丙,參數(shù)為名詞诵盼。使用注釋來解釋代碼。
## exercises
#1,
f1 <- function(string,prefix){
substr(string,1,nchar(prefix))==prefix
}
f3 <- function(x,y){
rep(y,length.out(x))
}
- 條件執(zhí)行(condition execution):if..else..語句
- if..else語句中使用邏輯表達(dá)式:&& 银还,||
- 向量化操作符: &,| 只可以用于多個(gè)值。
## exercise2歡迎函數(shù)
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){
###限定輸入的內(nèi)容格式
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)
}
}
- 函數(shù)的參數(shù):主要包括進(jìn)行計(jì)算的數(shù)據(jù)洁墙,控制計(jì)算過程的細(xì)節(jié)蛹疯,細(xì)節(jié)參數(shù)一般都有默認(rèn)值
n
## 使用近似正態(tài)分布計(jì)算均值兩端的置信區(qū)間
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))
}