从数据框中仅选择数字列

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


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

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


天涯尽头无女友
浏览 474回答 3
3回答

精慕HU

更新为避免使用不明智的sapply。由于数据框是一个列表,因此我们可以使用list-apply函数:nums <- unlist(lapply(x, is.numeric))&nbsp;&nbsp;然后是标准子集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的特殊问题,并且更直接,更健壮,可以在数据库后端的小标题上使用:dplyr::select_if(x, is.numeric)

交互式爱情

dplyr包的select_if()函数是一个优雅的解决方案:library("dplyr")select_if(x, is.numeric)
打开App,查看更多内容
随时随地看视频慕课网APP