假设你有一个像这样的data.frame:
x <- data.frame(v1=1:20,v2=1:20,v3=1:20,v4=letters[1:20])
Run Code Online (Sandbox Code Playgroud)
您如何仅选择x中的数字列?
mds*_*ner 264
编辑:更新,以避免使用不明智的sapply.
由于数据框是一个列表,我们可以使用list-apply函数:
nums <- unlist(lapply(x, is.numeric))
Run Code Online (Sandbox Code Playgroud)
然后是标准子集
x[ , nums]
## don't use sapply, even though it's less code
## nums <- sapply(x, is.numeric)
Run Code Online (Sandbox Code Playgroud)
对于一个更现代的现代R我现在推荐
x[ , purrr::map_lgl(x, is.numeric)]
Run Code Online (Sandbox Code Playgroud)
更少的代码,更少反映R的特殊怪癖,更简单,更强大,可用于数据库后端元素:
dplyr::select_if(x, is.numeric)
Run Code Online (Sandbox Code Playgroud)
Sha*_*ron 69
dplyr软件包的select_if(功能是一个优雅的解决方案:
library("dplyr")
select_if(x, is.numeric)
Run Code Online (Sandbox Code Playgroud)
Kev*_*rca 35
Filter() 从基础包是这个用例的完美功能:你只需要编码:
Filter(is.numeric, x)
Run Code Online (Sandbox Code Playgroud)
它也比以下快得多select_if():
library(microbenchmark)
microbenchmark(
dplyr::select_if(mtcars, is.numeric),
Filter(is.numeric, mtcars)
)
Run Code Online (Sandbox Code Playgroud)
返回(在我的计算机上)中位数为60微秒Filter,和21 000微秒select_if(更快350倍).
iris %>% dplyr::select(where(is.numeric)) #as per most recent updates
Run Code Online (Sandbox Code Playgroud)
另一种选择purrr是否定discard函数:
iris %>% purrr::discard(~!is.numeric(.))
Run Code Online (Sandbox Code Playgroud)
如果您想要数字列的名称,您可以添加names或colnames:
iris %>% purrr::discard(~!is.numeric(.)) %>% names
Run Code Online (Sandbox Code Playgroud)
这是其他答案的替代代码:
x[, sapply(x, class) == "numeric"]
Run Code Online (Sandbox Code Playgroud)
与 data.table
x[, lapply(x, is.numeric) == TRUE, with = FALSE]
Run Code Online (Sandbox Code Playgroud)
如果您只对列名感兴趣,请使用以下命令:
names(dplyr::select_if(train,is.numeric))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
160622 次 |
| 最近记录: |