select——按列篩選select()用列名作參數(shù)來(lái)選擇子集。 #加載包
library(dplyr)
library(tidyverse) #tidyverse是一個(gè)匯總包,其中包括了dplyr
#更好地?cái)?shù)據(jù)輸出顯示(以下兩種選其一即可)
iris <- tbl_df(iris)
iris <- as_tibble(iris)
iris
#直接選取列
select(iris, Petal.Length, Petal.Width)
select(iris, c(Petal.Length, Petal.Width))
#返回除Petal.Length和Petal.Width之外的所有列
select(iris, -Petal.Length, -Petal.Width)
select(iris, -c(Petal.Length, Petal.Width))
select(iris, !c(Petal.Length, Petal.Width))
#使用冒號(hào)連接列名,選擇多個(gè)列
select(iris, Sepal.Length:Petal.Width)
#使用冒號(hào)連接列名,不選擇這些
select(iris, !Sepal.Length:Petal.Width)
#選取變量名前綴包含Petal的列
select(iris, starts_with("Petal"))
#選取變量名前綴不包含Petal的列
select(iris, -starts_with("Petal"))
select(iris, !starts_with("Petal"))
#選取變量名后綴包含Width的列
select(iris, ends_with("Width"))
#選取變量名后綴不包含Width的列
select(iris, -ends_with("Width"))
select(iris, !ends_with("Width"))
#選取變量名中包含etal的列
select(iris, contains("etal"))
#選取變量名中不包含etal的列
select(iris, -contains("etal"))
select(iris, !contains("etal"))
#選取變量名前綴包含Petal和變量名后綴包含Width的列
select(iris, starts_with("Petal") & ends_with("Width"))
#選取變量名前綴包含Petal或變量名后綴包含Width的列
select(iris, starts_with("Petal") | ends_with("Width"))
#正則表達(dá)式匹配,返回變量名中包含t的列
select(iris, matches(".t."))
#正則表達(dá)式匹配,返回變量名中不包含t的列
select(iris, -matches(".t."))
select(iris, !matches(".t."))
#選擇字符向量中的列,select中不能直接使用字符向量篩選,需要使用one_of函數(shù)或者all_of函數(shù)
vars <- c("Petal.Length", "Petal.Width")
select(iris, one_of(vars))
select(iris, all_of(vars))
#返回指定字符向量之外的列
select(iris, -one_of(vars))
#返回所有列,一般調(diào)整數(shù)據(jù)集中變量順序時(shí)使用
select(iris, everything())
#調(diào)整列順序,把Species列放到最前面
select(iris, Species, everything())Reference
|
|
|
來(lái)自: 讀博怎么畢業(yè) > 《生信》