2017-12-29 39 views
0

2つのレベル( "はい"、 "いいえ")を持つすべての係数列を選択します。 これにdpylrを使用したいが、問題を解決できなかった。factor "No"、 "Yes"レベルを持つdplyrで複数の列を選択

AB %>% 
    select_if(.predicate = function(x) length(levels(x))==2 & unique(x) %in% c("No", "Yes")) 
+0

出発点として使用するサンプルデータを提供することはできますか?あなたの質問を解決するのを助けるのは難しいです。たとえそれが5〜10行だけであっても、あなたが 'AB 'であるものを提供しなければなりません。 – petergensler

答えて

1

unique(x) %in% c('No','Yes')なくスカラーより、unique(x)と同じ長さのベクトルを返します。

library(dplyr) 

# generate the dataframe with different factor levels 
n<-100 
no_yes  <- sample(c('No','Yes'),   n, replace = T) 
no_yes_maybe <- sample(c('No','Yes','Maybe'), n, replace = T) 
no   <- sample(c('No'),    n, replace = T) 
no_maybe  <- sample(c('No','Maybe'),  n, replace = T) 

AB<-data.frame(
    no_yes, # only this column should get returned 
    no_yes_maybe, 
    no, 
    no_maybe, 
    stringsAsFactors = T 
)%>%as.tbl 

# function to return TRUE if column has only No/Yes factors. 
desired_levels <- c('No','Yes') 
predicate_function <- function(x) setequal(levels(x),desired_levels) 

# use dplyr to select columns with desired factor levels 
AB%>%select_if(predicate_function) 
関連する問題