假设您有一个像这样的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中的数字列?
Answers:
编辑:更新为避免使用不当建议sapply
。
由于数据框是列表,因此我们可以使用list-apply函数:
nums <- unlist(lapply(x, is.numeric))
然后是标准子集
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)
undefined columns selected
。你如何避免呢?
tryCatch()
来处理此问题。请考虑打开一个新问题。
Filter()
来自基本软件包的代码是该用例的理想功能:您只需编写代码:
Filter(is.numeric, x)
它也比select_if()
:
library(microbenchmark)
microbenchmark(
dplyr::select_if(mtcars, is.numeric),
Filter(is.numeric, mtcars)
)
(在我的计算机上)返回的中位数为60微秒Filter
,返回为select_if
21000 微秒(快350倍)。
Filter()
行不通的是替换,例如Filter(is.numeric,iris) <- 0.5*Filter(is.numeric,iris)
行不通。
这是其他答案的替代代码:
x[, sapply(x, class) == "numeric"]
与一个 data.table
x[, lapply(x, is.numeric) == TRUE, with = FALSE]
library(purrr)
x <- x %>% keep(is.numeric)
库PCAmixdata具有functon splitmix,它可以分割给定数据帧“ YourDataframe”的定量(数值数据)和定性(类别数据),如下所示:
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)
如果因子变量很多,则可以使用select_if
函数。安装dplyr软件包。有许多功能可以通过满足条件来分离数据。您可以设置条件。
这样使用。
categorical<-select_if(df,is.factor)
str(categorical)
x[nums]
或x[sapply(x,is.numeric)]
也可以。他们总是回来data.frame
。比较x[1]
vs-x[,1]
第一个是data.frame
,第二个是向量。如果要防止转换,则必须使用x[, 1, drop=FALSE]
。