學(xué)習(xí)R包
概念
R包就是有著各種各樣函數(shù)工具的包,每一種包有的工具不一樣,有的還可以作圖,下載放在R中可以做各種數(shù)據(jù)分析和繪圖(就像下載好多筆刷畫畫一樣)
下載和安裝R包
下載
鏡像網(wǎng)站添加
教程鏈接
options("repos" = c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/")) #對應(yīng)清華源
options(BioC_mirror="https://mirrors.ustc.edu.cn/bioc/") #對應(yīng)中科大源
安裝
install.packages(“包”) 包存在于CRAN網(wǎng)站
BiocManager::install(“包”)包存在于Biocductor網(wǎng)站
加載
library(包)
dplyr的使用
五個基礎(chǔ)函數(shù)
- 增加列
> mutate(test, new = Sepal.Length * Sepal.Width)
Sepal.Length Sepal.Width
1 5.1 3.5
2 4.9 3.0
51 7.0 3.2
52 6.4 3.2
101 6.3 3.3
102 5.8 2.7
Petal.Length Petal.Width
1 1.4 0.2
2 1.4 0.2
51 4.7 1.4
52 4.5 1.5
101 6.0 2.5
102 5.1 1.9
Species new
1 setosa 17.85
2 setosa 14.70
51 versicolor 22.40
52 versicolor 20.48
101 virginica 20.79
102 virginica 15.66
- 按列篩選
> select(test,1)
Sepal.Length
1 5.1
2 4.9
51 7.0
52 6.4
101 6.3
102 5.8
- 按行篩選
> filter(test,Species=="setosa")
Sepal.Length Sepal.Width
1 5.1 3.5
2 4.9 3.0
Petal.Length Petal.Width
1 1.4 0.2
2 1.4 0.2
Species
1 setosa
2 setosa
> filter(test, Species == "setosa"&Sepal.Length > 5 )
Sepal.Length Sepal.Width
1 5.1 3.5
Petal.Length Petal.Width
1 1.4 0.2
Species
1 setosa
> filter(test, Species %in% c("setosa","versicolor"))
Sepal.Length Sepal.Width
1 5.1 3.5
2 4.9 3.0
3 7.0 3.2
4 6.4 3.2
Petal.Length Petal.Width
1 1.4 0.2
2 1.4 0.2
3 4.7 1.4
4 4.5 1.5
Species
1 setosa
2 setosa
3 versicolor
4 versicolor
- 排序
arrange(test, Sepal.Length)#默認(rèn)從小到大排序
arrange(test, desc(Sepal.Length))#用desc從大到小 - 數(shù)據(jù)匯總(就是把表中的數(shù)據(jù)拿來加減乘除)
> summarise(test, mean(Sepal.Length), sd(Sepal.Length))
mean是平均數(shù),sd是標(biāo)準(zhǔn)差
兩個實用技能
- 讓代碼減少再減少的魔法(管道操作%>%)
test %>%
group_by(Species) %>%
summarise(mean(Sepal.Length), sd(Sepal.Length))
%>%意思是,把test中的數(shù)據(jù)依次應(yīng)用于group函數(shù),summarise函數(shù),就不用把test引用兩次,如果不用這個,上面的代碼就長這樣?
summarise(group_by(test, Species),mean(Sepal.Length), sd(Sepal.Length))
- 計數(shù)的魔法
> count(test,Species)
Species n
1 setosa 2
2 versicolor 2
3 virginica 2
兩個表取交集
制表
options(stringsAsFactors = F)
test1 <- data.frame(x = c('b','e','f','x'),
z = c("A","B","C",'D'),
stringsAsFactors = F)
stringsAsFactors = F意思是不引入Factor
- 內(nèi)連inner_join,取交集
> inner_join(test1, test2, by = "x")
x z y
1 b A 2
2 e B 5
3 f C 6
取交集,只顯示兩個表相同的內(nèi)容
- 左連left_join
> left_join(test1,test2,by='x')
x z y
1 b A 2
2 e B 5
3 f C 6
4 x D NA
test2粘在test1左邊,test1全部顯示,test2只顯示和test1有交集的部分
- 全連full_join
> full_join( test2, test1, by = 'x')
x y z
1 a 1 <NA>
2 b 2 A
3 c 3 <NA>
4 d 4 <NA>
5 e 5 B
6 f 6 C
7 x NA D
全部寫出來,test1和test2不匹配的內(nèi)容就讓他空著,相同的就合并
- 半連接:返回能夠與y表匹配的x表所有記錄semi_join
> semi_join(x = test2, y = test1, by = 'x')
x y
1 b 2
2 e 5
3 f 6
就是把x表和y表匹配一下,再把xy表中都有的以x表形式寫出來
- 反連接:返回?zé)o法與y表匹配的x表的所記錄anti_join
> anti_join(x = test1, y = test2, by = 'x')
x z
1 x D
就是把x表和y表匹配一下,再把x表中有的y中沒有的寫出來
簡單合并
- 合并列(行要相同)
> bind_cols(test1, test3)
x y z
1 1 10 100
2 2 20 200
3 3 30 300
4 4 40 400
- 合并行(列要相同)
> bind_rows(test1, test2)
x y
1 1 10
2 2 20
3 3 30
4 4 40
5 5 50
6 6 60
思維導(dǎo)圖

day6 R包的使用.png