是否可以在 R 中的一次调用中按条件选择一个变量,然后选择其他一些变量?

Ale*_*era 2 select r subset lapply

我正在使用flights库中包含的nycflights13数据库,我认为手动选择一个(或任意数量)变量然后按条件选择其他一些变量(例如“载体”,然后是所有数字变量)可能会很有趣. 这可以分三步完成,例如:

library(nycflights13)
data(flights)
flights
a <- flights[,"carrier", drop=FALSE]
b <- flights[, lapply(flights,is.numeric) == TRUE, drop=FALSE]
ab <- cbind(a,b)
str(ab) # 'data.frame':   336776 obs. of  15 variables:
Run Code Online (Sandbox Code Playgroud)

但这不起作用:

flights[, "carrier" & c(lapply(flights,is.numeric)) == TRUE, drop=FALSE]
flights[, "carrier" & lapply(flights,is.numeric) == TRUE, drop=FALSE]

Error in "carrier" & lapply(flights, is.numeric) == TRUE : 
  solo son posibles operaciones para variables de tipo numérico, compleja o lógico
Run Code Online (Sandbox Code Playgroud)

我必须说select_iffromtidyverse也没有用。

所以我的问题是:是否有可能在一次通话中实现我想要做的事情以及如何做到?感谢您的任何意见或建议

akr*_*run 5

取而代之的是lapply,我们可以使用sapply. 它将给出一个逻辑输出,使用它来提取名称或使用which,然后与“载体”连接

flights[, c("carrier", names(flights)[sapply(flights, is.numeric)]) , drop=FALSE]
Run Code Online (Sandbox Code Playgroud)

drop是不需要tibble因为默认情况下它不会降


随着dplyr一个选项

library(dplyr)
flights %>% 
       select(carrier,  select_if(., is.numeric) %>% names)
Run Code Online (Sandbox Code Playgroud)