原文鏈接:https://predictivehacks.com/tidyverse-tips/
tidyverse包對于數(shù)據(jù)處理非常有用鸿捧,是個(gè)好的生產(chǎn)力工具锹安。有些小竅門可以mark一下忽妒,以備日后使用。
(1) select_if|rename if
例子:如果你想在數(shù)據(jù)變量的列名前加前綴“numeric_”姊舵。
library(tidyverse)
iris%>%select_if(is.numeric, list(~ paste0("numeric_", .)))%>%head()
numeric_Sepal.Length numeric_Sepal.Width numeric_Petal.Length numeric_Petal.Width
1 5.1 3.5 1.4 0.2
2 4.9 3.0 1.4 0.2
3 4.7 3.2 1.3 0.2
4 4.6 3.1 1.5 0.2
5 5.0 3.6 1.4 0.2
6 5.4 3.9 1.7 0.4
可以用rename_if達(dá)到同樣的目的。
(2)everything
有時(shí)候想讓指定的列放到第一列或最后一列寓落,可以用everything()來實(shí)現(xiàn)括丁。例如:要讓iris數(shù)據(jù)中Species放到數(shù)據(jù)的第一列:
mydataset<-iris%>%select(Species, everything())
mydataset%>%head()
Species Sepal.Length Sepal.Width Petal.Length Petal.Width
1 setosa 5.1 3.5 1.4 0.2
2 setosa 4.9 3.0 1.4 0.2
3 setosa 4.7 3.2 1.3 0.2
4 setosa 4.6 3.1 1.5 0.2
5 setosa 5.0 3.6 1.4 0.2
6 setosa 5.4 3.9 1.7 0.4
放最后一列
mydataset%>%select(-Species, everything())%>%head()
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
(3)relocate
可以精確的把某一列放到另一列之前或之后。舉例:把Petal.Width放到 Sepal.Width之后伶选。
iris%>%relocate(Petal.Width, .after=Sepal.Width)%>%head()
Sepal.Length Sepal.Width Petal.Width Petal.Length Species
1 5.1 3.5 0.2 1.4 setosa
2 4.9 3.0 0.2 1.4 setosa
3 4.7 3.2 0.2 1.3 setosa
4 4.6 3.1 0.2 1.5 setosa
5 5.0 3.6 0.2 1.4 setosa
6 5.4 3.9 0.4 1.7 setosa
把Petal.Width放到最后
iris%>%relocate(Petal.Width, .after=last_col())%>%head()
Sepal.Length Sepal.Width Petal.Length Species Petal.Width
1 5.1 3.5 1.4 setosa 0.2
2 4.9 3.0 1.4 setosa 0.2
3 4.7 3.2 1.3 setosa 0.2
4 4.6 3.1 1.5 setosa 0.2
5 5.0 3.6 1.4 setosa 0.2
6 5.4 3.9 1.7 setosa 0.4
(4)pull
有時(shí)候我們用數(shù)據(jù)框史飞,需要選擇一列作為輸出向量,可以用pull做到這一點(diǎn)仰税。例子:如果想要用t.test比較兩種鳶尾花setosa 和 virginica的Sepal.Length构资,可以這么做。
setosa_sepal_length<-iris%>%filter(Species=='setosa')%>%select(Sepal.Length)%>%pull()
virginica_sepal_length<-iris%>%filter(Species=='virginica')%>%select(Sepal.Length)%>%pull()
t.test(setosa_sepal_length,virginica_sepal_length)
data: setosa_sepal_length and virginica_sepal_length
t = -15.386, df = 76.516, p-value < 2.2e-16
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
-1.78676 -1.37724
sample estimates:
mean of x mean of y
5.006 6.588
(5) reorder
用ggplot2的時(shí)候有時(shí)根據(jù)特定的條件排序某些因子讓人沮喪陨簇。比如我們以Species來繪制Sepal.Width的箱線圖:
iris%>%ggplot(aes(x=Species, y=Sepal.Width))+geom_boxplot()
image.png
假如以Species的中位數(shù)重新排序吐绵,可以用reorder()函數(shù):
iris%>%ggplot(aes(x=reorder(Species,Sepal.Width, FUN = median), y=Sepal.Width))+geom_boxplot()+xlab("Species")
image.png
是不是很方便!:诱馈己单!