R包
一、R studio預設鏡像
1.設置
file.edit('~/.Rprofile')
options("repos" = c(CRAN="https://mirrors.tuna.tsinghua.edu.cn/CRAN/")) #對應清華源
options(BioC_mirror="https://mirrors.ustc.edu.cn/bioc/") #對應中科大源
2.查看設置
options()$repos
options()$BioC_mirror
聽說設置是否成功全靠緣分,我可能只有一半緣分
image.png
二、dplyr包——計算,數據整理
1.添加列
mutate(test, new = Sepal.Length * Sepal.Width)
2.篩選
#按列號篩選
select(test,1)
select(test,c(1,5))
select(test,Sepal.Length)
#按列名篩選
select(test, Petal.Length, Petal.Width)
vars <- c("Petal.Length", "Petal.Width")#var是"Petal.Length", "Petal.Width"
select(test, one_of(vars))
#用filter篩選行
filter(test, Species == "setosa")#在test中篩選spcies值未setosa的行
filter(test, Species == "setosa"&Sepal.Length > 5 )
#a %in%b,取a在b中的值
filter(test, Species %in% c("setosa","versicolor"))
3.排序
arrange(test, Sepal.Length)#默認從小到大排序
arrange(test, desc(Sepal.Length))#用desc從大到小
4.匯總,分組
summarise(test, mean(Sepal.Length), sd(Sepal.Length))# 計算Sepal.Length的平均值和標準差
# 先按照Species分組,計算每組Sepal.Length的平均值和標準差
group_by(test, Species)
summarise(group_by(test, Species),mean(Sepal.Length), sd(Sepal.Length))
三、管道操作
#管道操作%>% (cmd/ctr + shift + M)
#%>% 直接把數據傳遞給下一個公式,任意一個tidyverse包可用
test %>%
group_by(Species) %>%
summarise(mean(Sepal.Length), sd(Sepal.Length))
count(test,Species)
四、關聯數據
操作關系數據不要引入factor
options(stringsAsFactors = F)
1.連接
#內連inner,取交集
inner_join(test1, test2, by = "x")
#左連left
left_join(test1, test2, by = 'x')
left_join(test2, test1, by = 'x')
#全連full
full_join( test1, test2, by = 'x')
#半連接:返回能夠與y表匹配的x表所有記錄
semi_join(x = test1, y = test2, by = 'x')
#反連接:返回無法與y表匹配的x表的所記錄
anti_join(x = test2, y = test1, by = 'x')
2.合并
bind_rows()
bind_cols()
今日小結
image.png