假设只选择数值列,你有这样的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是数字的那些列?
由于数据帧是一个列表,我们可以使用该列表,应用功能:
nums <- sapply(x, is.numeric)
从基部包然后标准子集
x[ , nums]
Filter()
是针对使用 - 功能完善案例: 您只需代码:
Filter(is.numeric, x)
它也比select_if()
快得多:
library(microbenchmark)
microbenchmark(
dplyr::select_if(mtcars, is.numeric),
Filter(is.numeric, mtcars)
)
回报(我的电脑上)的60微秒Filter
中位数,而21 000微秒dplyr
(350X更快)。
这个交替代码给其他答案:
x[, sapply(x, class) == "numeric"]
与data.table
x[, lapply(x, is.numeric) == TRUE, with = FALSE]
'training'从哪里来?不应该读'x'吗? – Uwe 2016-11-13 16:16:41
确定复制并粘贴并且不检查问题 – 2016-11-13 16:22:54
这是对选定答案的更多评论,而不是唯一答案。 – 2016-11-13 17:55:14
的dplyr包的select_if(
)函数是一个优雅的解决方案:
library("dplyr")
select_if(x, is.numeric)
这是我的解决方案,但它看起来像'select_if()'现在已经折旧了。 – ApeWithPants 2018-01-03 18:23:03
如果你有很多因素变量,你可以使用select_if
功能。 安装dplyr软件包。有许多功能通过满足条件来分隔数据。你可以设置条件。
像这样使用。
categorical<-select_if(df,is.factor)
str(categorical)
看起来像这个较早的答案的副本http://stackoverflow.com/a/40808873/170352 – 2017-01-06 04:07:09
PCAmixdata已functon一个给定的数据帧“YourDataframe”的splitmix其将量化(数值数据)和定性(分类数据),如下所示的库:
install.packages("PCAmixdata")
library(PCAmixdata)
split <- splitmix(YourDataframe)
X1 <- split$X.quanti(Gives numerical columns in the dataset)
X2 <- split$X.quali (Gives categorical columns in the dataset)
谢谢,我发现有一个刚因为你发布它x [,sapply(x,is.numeric)] – 2011-05-02 22:31:12
'x [nums]'或'x [sapply(x,is.numeric)]'也适用。他们总是返回'data.frame'。比较'x [1]'和'x [,1]' - 第一个是data.frame,第二个是矢量。如果想阻止转换,那么必须使用'x [,1,drop = FALSE]'。 – Marek 2011-05-03 11:46:47
“!is.numeric”是否工作? – PatrickT 2013-11-29 10:17:32