R dpylr select_if具有多个条件 [英] R dpylr select_if with multiple conditions

查看:577
本文介绍了R dpylr select_if具有多个条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按名称选择所有数字变量以及一些变量.我设法使用select_if来获取数字变量,并选择通过名称来获取数字变量,但是无法将两者合并为一条语句

I would like to select all numeric variables as well as some variables by name. I have managed to use select_if to get the numeric variables and select to get the ones by name but can't combine the two into one statement

x = data.table(c(1,2,3),c(10,11,12),c('a','b','c'),c('x','y','z'), c('l', 'm','n'))

我希望我的结果是:

V1 V2 V4 V5
1 10  x l
2 11  y m
3 12  z n

我试过了,但是没用

y = x %>%
select_if(is.numeric, V4, V5)

推荐答案

如果我们有数据框,则x:

If we have a data frame, x:

x = data.frame(V1=c(1,2,3),V2=c(10,11,12),V3=c('a','b','c'),V4=c('x','y','z'),V5=c('l', 'm','n'), stringsAsFactors=FALSE)
##  V1 V2 V3 V4 V5
##1  1 10  a  x  l
##2  2 11  b  y  m
##3  3 12  c  z  n

其中V1V2实际上是numeric,其余列不是因素,那么我们可以这样做:

where V1 and V2 are actually numeric and the rest of the columns are not factors, then we can do:

library(dplyr)
y <- x %>% select_if(function(col) is.numeric(col) | 
                                   all(col == .$V4) | 
                                   all(col == .$V5))
##  V1 V2 V4 V5
##1  1 10  x  l
##2  2 11  y  m
##3  3 12  z  n

并不是说这是最好的方法,但它确实可以完成您想要的操作.这里的问题是select_if希望其函数返回与所有列相对应的布尔向量.

Not saying that this is the best thing to do, but it does do what you want. The issue here is that select_if expects its function to return a boolean vector corresponding to all columns.

另一种方法是使用select:

y <- x %>% select(which(sapply(.,class)=="numeric"),V4,V5)
##  V1 V2 V4 V5
##1  1 10  x  l
##2  2 11  y  m
##3  3 12  z  n

这可能更好.

这篇关于R dpylr select_if具有多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆