[英]Selecting only numeric columns from a data frame
假設,你有一個這樣的 data.frame:
x <- data.frame(v1=1:20,v2=1:20,v3=1:20,v4=letters[1:20])
您將如何 select 只有 x 中的那些列是數字?
編輯:更新以避免使用不明智的sapply
。
由於數據框是一個列表,我們可以使用 list-apply 函數:
nums <- unlist(lapply(x, is.numeric), use.names = FALSE)
然后標准子集
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 也支持以下語法:
x %>% dplyr::select(where(is.numeric))
dplyr 包的select_if(
) function 是一個優雅的解決方案:
library("dplyr")
select_if(x, is.numeric)
來自基礎 package 的Filter()
是該用例的完美 function :您只需編寫代碼:
Filter(is.numeric, x)
它也比select_if()
快得多:
library(microbenchmark)
microbenchmark(
dplyr::select_if(mtcars, is.numeric),
Filter(is.numeric, mtcars)
)
返回(在我的計算機上) Filter
的中位數為 60 微秒, select_if
的中位數為 21 000 微秒(快 350 倍)。
如果您只對列名感興趣,請使用:
names(dplyr::select_if(train,is.numeric))
iris %>% dplyr::select(where(is.numeric)) #as per most recent updates
purrr
的另一個選項是否定discard
function:
iris %>% purrr::discard(~!is.numeric(.))
如果您想要數字列的名稱,可以添加names
或colnames
:
iris %>% purrr::discard(~!is.numeric(.)) %>% names
這是其他答案的替代代碼:
x[, sapply(x, class) == "numeric"]
與data.table
x[, lapply(x, is.numeric) == TRUE, with = FALSE]
library(purrr)
x <- x %>% keep(is.numeric)
庫 PCAmixdata 具有拆分給定 dataframe“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)
如果你有很多因子變量,你可以使用select_if
函數。 安裝 dplyr 包。 通過滿足條件來分離數據的 function 有很多。 你可以設置條件。
像這樣使用。
categorical<-select_if(df,is.factor)
str(categorical)
另一種方法可能如下:-
#extracting numeric columns from iris datset
(iris[sapply(iris, is.numeric)])
Numerical_variables <- which(sapply(df, is.numeric))
# then extract column names
Names <- names(Numerical_variables)
這不會直接回答問題,但可能非常有用,特別是如果您想要除 id 列和因變量之外的所有數字列。
numeric_cols <- sapply(dataframe, is.numeric) %>% which %>%
names %>% setdiff(., c("id_variable", "dep_var"))
dataframe %<>% dplyr::mutate_at(numeric_cols, function(x) your_function(x))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.