我有一個簡單的數據幀象下面這樣:強制多列因素在一次
data <- data.frame(matrix(sample(1:40), 4, 10, dimnames = list(1:4, LETTERS[1:10])))
我想知道我怎麼能選擇多列,並將它們一起轉換爲因素。我通常按照像data$A = as.factor(data$A)
這樣的方式來做。但是,當數據幀非常大並且包含大量列時,這種方式將非常耗時。有誰知道是否有任何聰明的方式來做到這一點?
我有一個簡單的數據幀象下面這樣:強制多列因素在一次
data <- data.frame(matrix(sample(1:40), 4, 10, dimnames = list(1:4, LETTERS[1:10])))
我想知道我怎麼能選擇多列,並將它們一起轉換爲因素。我通常按照像data$A = as.factor(data$A)
這樣的方式來做。但是,當數據幀非常大並且包含大量列時,這種方式將非常耗時。有誰知道是否有任何聰明的方式來做到這一點?
選擇一些列強迫因素:
cols <- c("A", "C", "D", "H")
使用lapply()
強迫和更換所選列:
data[cols] <- lapply(data[cols], factor)
檢查結果:
sapply(data, class)
# A B C D E F G
# "factor" "integer" "factor" "factor" "integer" "integer" "integer"
# H I J
# "factor" "integer" "integer"
這裏是一個選項使用dplyr
。 magrittr
的%<>%
運算符用生成的值更新lhs對象。
library(magrittr)
library(dplyr)
cols <- c("A", "C", "D", "H")
data %<>%
mutate_each_(funs(factor(.)),cols)
str(data)
#'data.frame': 4 obs. of 10 variables:
# $ A: Factor w/ 4 levels "23","24","26",..: 1 2 3 4
# $ B: int 15 13 39 16
# $ C: Factor w/ 4 levels "3","5","18","37": 2 1 3 4
# $ D: Factor w/ 4 levels "2","6","28","38": 3 1 4 2
# $ E: int 14 4 22 20
# $ F: int 7 19 36 27
# $ G: int 35 40 21 10
# $ H: Factor w/ 4 levels "11","29","32",..: 1 4 3 2
# $ I: int 17 1 9 25
# $ J: int 12 30 8 33
或者,如果我們使用data.table
,無論是使用for
循環與set
setDT(data)
for(j in cols){
set(data, i=NULL, j=j, value=factor(data[[j]]))
}
或者,我們可以在.SDcols
指定 '的cols' 和分配(:=
)的RHS爲「 cols'
setDT(data)[, (cols):= lapply(.SD, factor), .SDcols=cols]
更近tidyverse
方式是使用mutate_at
功能:
library(tidyverse)
library(magrittr)
set.seed(88)
data <- data.frame(matrix(sample(1:40), 4, 10, dimnames = list(1:4, LETTERS[1:10])))
cols <- c("A", "C", "D", "H")
data %<>% mutate_at(cols, funs(factor(.)))
str(data)
$ A: Factor w/ 4 levels "5","17","18",..: 2 1 4 3
$ B: int 36 35 2 26
$ C: Factor w/ 4 levels "22","31","32",..: 1 2 4 3
$ D: Factor w/ 4 levels "1","9","16","39": 3 4 1 2
$ E: int 3 14 30 38
$ F: int 27 15 28 37
$ G: int 19 11 6 21
$ H: Factor w/ 4 levels "7","12","20",..: 1 3 4 2
$ I: int 23 24 13 8
$ J: int 10 25 4 33
。爲更完整,並與問候this question asking about changing string columns only,有mutate_if
:
data <- cbind(stringVar = sample(c("foo","bar"),10,replace=TRUE),
data.frame(matrix(sample(1:40), 10, 10, dimnames = list(1:10, LETTERS[1:10]))),stringsAsFactors=FALSE)
factoredData = data %>% mutate_if(is.character,funs(factor(.)))
如果從值獲得的另一個目的表格然後使用它們進行轉換,可以嘗試以下方法
### pre processing
ind <- bigm.train[,lapply(.SD,is.character)]
ind <- names(ind[,.SD[T]])
### Convert multiple columns to factor
bigm.train[,(ind):=lapply(.SD,factor),.SDcols=ind]
這個選擇ects列是專門基於字符的,然後將它們轉換爲因子。
是不是需要'data [,cols] < - lapply(data [,cols],factor)'(列的前導逗號)? – Tgsmith61591
@ Tgsmith61591-它可能是。用逗號是矩陣類型的子集,不用逗號就是列表子集。數據框可以被任何一個子集,所以任何一種方式都可以工作。 –