假设,你有一个这样的data.frame:

x <- data.frame(v1=1:20,v2=1:20,v3=1:20,v4=letters[1:20])

如何只选择x中的数字列呢?


当前回答

这是其他答案的替代代码:

x[, sapply(x, class) == "numeric"]

用一个数据表

x[, lapply(x, is.numeric) == TRUE, with = FALSE]

其他回答

PCAmixdata库有一个splitmix函数,它可以对给定的数据框架“YourDataframe”进行定量(数值数据)和定性(分类数据)的拆分,如下所示:

install.packages("PCAmixdata")
library(PCAmixdata)
split <- splitmix(YourDataframe)
X1 <- split$X.quanti(Gives numerical columns in the dataset) 
X2 <- split$X.quali (Gives categorical columns in the dataset)

这并不能直接回答问题,但非常有用,特别是当你想要除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))

来自基本包的Filter()是该用例的完美函数: 你只需要编写代码:

Filter(is.numeric, x)

它也比select_if()快得多:

library(microbenchmark)
microbenchmark(
    dplyr::select_if(mtcars, is.numeric),
    Filter(is.numeric, mtcars)
)

Filter返回(在我的计算机上)中值为60微秒,select_if返回21 000微秒(快350倍)。

如果你有很多因子变量,你可以使用select_if函数。 安装dplyr包。有许多函数通过满足一个条件来分离数据。你可以设置条件。

像这样使用。

categorical<-select_if(df,is.factor)
str(categorical)

另一种方法可能如下:-

#extracting numeric columns from iris datset
(iris[sapply(iris, is.numeric)])