根据某些值的 presence/absence 从数据框中删除列

Deleting columns from a data frame based on presence/absence of certain values

我想通过删除满足或不满足特定条件的列来对数据框进行子集化。例如,给定以下数据:

df <- data.frame(w = c('a', 'b', 'c'), 
                 x = c(1, 0, 0), 
                 y = c(0, 1, 0), 
                 z = c(0, 0, 1))

给出:

  w x y z
  a 1 0 0
  b 0 1 0
  c 0 0 1

我想在对行进行子集化后删除包含 0 的列。例如:

df %>% filter(., w == 'a')

产生:

w x y z
a 1 0 0

然后我想减少到:

x
1

我希望使用 dplyr 执行此操作,因此下一步应该在 filter 命令之后进行。我曾尝试将 summarise 与 apply 结合使用,但没有奏效。

您可以使用 select_if():

df %>% filter(w == 'a') %>% select_if(function(col) is.numeric(col) && all(col != 0))

#  x
#1 1