學(xué)習(xí)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包學(xué)習(xí)
五個基礎(chǔ)函數(shù)
新增列 mutate()
篩選列 select()
篩選行 filter()
表格排序 arrange()
匯總 summarise()
內(nèi)置數(shù)據(jù)集:R內(nèi)置了大量數(shù)據(jù)集和案例浑测,這樣在學(xué)習(xí)的時候,無需自己去找數(shù)據(jù)集歪玲,就可以根據(jù)案例來進(jìn)行操作迁央。下面的示例數(shù)據(jù)直接使用內(nèi)置數(shù)據(jù)集iris。
%in% :x %in% y 的意思是“對x里的每個元素進(jìn)行判斷滥崩,判斷它是否在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)#默認(rèn)從小到大排序
arrange(test, desc(Sepal.Length))#用desc從大到小
summarise(test, mean(Sepal.Length), sd(Sepal.Length))# 計算Sepal.Length的平均值和標(biāo)準(zhǔn)差
dplyr兩個實(shí)用技能
%>% : 管道符號,表示前一句代碼的輸出作為后一句代碼的輸入短条,查看http://www.reibang.com/p/5a5e2fe99cd2导匣。快捷鍵 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ù)值屹蚊,當(dāng)相應(yīng)的值不存在的時候,用NA代替进每;
c. 全連
full_join( test1, test2, by = 'x')
全連保留了所有x對應(yīng)的數(shù)據(jù)汹粤,當(dāng)相應(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')
返回?zé)o法與y表匹配的x表的所記錄anti_join
f. 簡單合并
bind_rows(test1, test2)