从数据框中仅选择数字列 [英] Selecting only numeric columns from a data frame

查看:36
本文介绍了从数据框中仅选择数字列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose, you have a data.frame like this:

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

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

How would you select only those columns in x that are numeric?

推荐答案

更新以避免使用不明智的sapply.

updated to avoid use of ill-advised sapply.

由于数据框是一个列表,我们可以使用 list-apply 函数:

Since a data frame is a list we can use the list-apply functions:

nums <- unlist(lapply(x, is.numeric))  

然后是标准子集

x[ , nums]

## don't use sapply, even though it's less code
## nums <- sapply(x, is.numeric)

对于更惯用的现代 R,我现在推荐

For a more idiomatic modern R I'd now recommend

x[ , purrr::map_lgl(x, is.numeric)]

更少的代码,更少地反映 R 的特殊怪癖,并且更直接、更健壮,可用于数据库后端小程序:

Less codey, less reflecting R's particular quirks, and more straightforward, and robust to use on database-back-ended tibbles:

dplyr::select_if(x, is.numeric)

较新版本的 dplyr,也支持以下语法:

Newer versions of dplyr, also support the following syntax:

x %>% dplyr::select(where(is.numeric))

这篇关于从数据框中仅选择数字列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆