假设,你有一个这样的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中的数字列呢?
当前回答
编辑:更新,以避免使用不明智的应用。
由于数据帧是一个列表,我们可以使用list-apply函数:
nums <- unlist(lapply(x, is.numeric), use.names = FALSE)
然后是标准子集
x[ , nums]
## don't use sapply, even though it's less code
## nums <- sapply(x, is.numeric)
对于一个更习惯的现代R,我现在推荐
x[ , purrr::map_lgl(x, is.numeric)]
更少的可编程性,更少的反映R的特殊癖好,更直接,更健壮地用于数据库后端tibbles:
dplyr::select_if(x, is.numeric)
新版本的dplyr也支持以下语法:
x %>% dplyr::select(where(is.numeric))
其他回答
另一种方法可能如下:-
#extracting numeric columns from iris datset
(iris[sapply(iris, is.numeric)])
dplyr包的select_if()函数是一个优雅的解决方案:
library("dplyr")
select_if(x, is.numeric)
这是其他答案的替代代码:
x[, sapply(x, class) == "numeric"]
用一个数据表
x[, lapply(x, is.numeric) == TRUE, with = FALSE]
如果你只对列名感兴趣,那么使用这个:
names(dplyr::select_if(train,is.numeric))
Numerical_variables <- which(sapply(df, is.numeric))
# then extract column names
Names <- names(Numerical_variables)