學習R包
安裝和載入R包
1、鏡像配置的高級方式
配置Rprofile文件,配置完成后保存重啟即可。
file.edit('~/.Rprofile') #編輯文件
options("repos" = c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/")) #對應(yīng)清華源
options(BioC_mirror="https://mirrors.ustc.edu.cn/bioc/") #對應(yīng)中科大源
2、安裝
install.packages(“包”)或BiocManager::install(“包”)
3、載入
library()或require()
dplyr包學習
五個基礎(chǔ)函數(shù)
新增列 mutate()
篩選列 select()
篩選行 filter()
表格排序 arrange()
匯總 summarise()
內(nèi)置數(shù)據(jù)集:R內(nèi)置了大量數(shù)據(jù)集和案例,這樣在學習的時候,無需自己去找數(shù)據(jù)集,就可以根據(jù)案例來進行操作。下面的示例數(shù)據(jù)直接使用內(nèi)置數(shù)據(jù)集iris。
%in% :x %in% y 的意思是“對x里的每個元素進行判斷,判斷它是否在y中存在,存在就返回TRUE,不存在就返回FALSE”。
test <- iris[c(1:2,51:52,101:102),]
mutate(test, new = Sepal.Length * Sepal.Width) #新增列
select(test,1) #篩選第一列
select(test,c(1,5)) #篩選第一列和第五列
select(test,Sepal.Length) #篩選Sepal.Length列
filter(test, Species == "setosa") #篩選species列為setosa的行
filter(test, Species == "setosa"&Sepal.Length > 5 )# 篩選species列為setosa,length>5的行
filter(test, Species %in% c("setosa","versicolor")) #篩選species列存在setosa和versicolor的行
arrange(test, Sepal.Length)#默認從小到大排序
arrange(test, desc(Sepal.Length))#用desc從大到小
summarise(test, mean(Sepal.Length), sd(Sepal.Length))# 計算Sepal.Length的平均值和標準差
dplyr兩個實用技能
%>% : 管道符號,表示前一句代碼的輸出作為后一句代碼的輸入,查看http://www.itdecent.cn/p/5a5e2fe99cd2??旖萱I cmd/ctr + shift + M。
1、管道操作
test %>%
group_by(Species) %>%
summarise(mean(Sepal.Length), sd(Sepal.Length))
2、統(tǒng)計某列的unique值
count(test,Species)
dplyr處理關(guān)系數(shù)據(jù)
a. 內(nèi)連
inner_join(test1, test2, by = "x")
基于x的連接只保留共同的數(shù)據(jù)
b. 左連
left_join(test1, test2, by = 'x')
只保留了test1的x對應(yīng)的數(shù)值,當相應(yīng)的值不存在的時候,用NA代替;
c. 全連
full_join( test1, test2, by = 'x')
全連保留了所有x對應(yīng)的數(shù)據(jù),當相應(yīng)的值不存在的時候,用NA代替
d. 半連接
semi_join(x = test1, y = test2, by = 'x')
返回能夠與y表匹配的x表所有記錄semi_join
e. 反連接
anti_join(x = test2, y = test1, by = 'x')
返回無法與y表匹配的x表的所記錄anti_join
f. 簡單合并
bind_rows(test1, test2)