假设,你有一个这样的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)
其他回答
dplyr包的select_if()函数是一个优雅的解决方案:
library("dplyr")
select_if(x, is.numeric)
这是其他答案的替代代码:
x[, sapply(x, class) == "numeric"]
用一个数据表
x[, lapply(x, is.numeric) == TRUE, with = FALSE]
iris %>% dplyr::select(where(is.numeric)) #as per most recent updates
purrr的另一个选项是否定丢弃函数:
iris %>% purrr::discard(~!is.numeric(.))
如果你想要数值列的名称,你可以添加名称或冒号:
iris %>% purrr::discard(~!is.numeric(.)) %>% names
如果你只对列名感兴趣,那么使用这个:
names(dplyr::select_if(train,is.numeric))
Numerical_variables <- which(sapply(df, is.numeric))
# then extract column names
Names <- names(Numerical_variables)