假设,你有一个这样的data.frame:
x <- data.frame(v1=1:20,v2=1:20,v3=1:20,v4=letters[1:20])
如何只选择x中的数字列呢?
假设,你有一个这样的data.frame:
x <- data.frame(v1=1:20,v2=1:20,v3=1:20,v4=letters[1:20])
如何只选择x中的数字列呢?
当前回答
dplyr包的select_if()函数是一个优雅的解决方案:
library("dplyr")
select_if(x, is.numeric)
其他回答
iris %>% dplyr::select(where(is.numeric)) #as per most recent updates
purrr的另一个选项是否定丢弃函数:
iris %>% purrr::discard(~!is.numeric(.))
如果你想要数值列的名称,你可以添加名称或冒号:
iris %>% purrr::discard(~!is.numeric(.)) %>% names
如果你有很多因子变量,你可以使用select_if函数。 安装dplyr包。有许多函数通过满足一个条件来分离数据。你可以设置条件。
像这样使用。
categorical<-select_if(df,is.factor)
str(categorical)
这并不能直接回答问题,但非常有用,特别是当你想要除id列和因变量外的所有数字列时。
numeric_cols <- sapply(dataframe, is.numeric) %>% which %>%
names %>% setdiff(., c("id_variable", "dep_var"))
dataframe %<>% dplyr::mutate_at(numeric_cols, function(x) your_function(x))
Numerical_variables <- which(sapply(df, is.numeric))
# then extract column names
Names <- names(Numerical_variables)
library(purrr)
x <- x %>% keep(is.numeric)