Tyl*_*ker 177
嗨欢迎来到R.世界
mtcars #look at this built in data set
str(mtcars) #allows you to see the classes of the variables (all numeric)
#one approach it to index with the $ sign and the as.factor function
mtcars$am <- as.factor(mtcars$am)
#another approach
mtcars[, 'cyl'] <- as.factor(mtcars[, 'cyl'])
str(mtcars) # now look at the classes
Run Code Online (Sandbox Code Playgroud)
这也适用于字符,日期,整数和其他类
由于你是R的新手我建议你看看这两个网站:
R参考手册: http ://cran.r-project.org/manuals.html
R参考卡: http ://cran.r-project.org/doc/contrib/Short-refcard.pdf
42-*_*42- 84
# To do it for all names
df[] <- lapply( df, factor) # the "[]" keeps the dataframe structure
col_names <- names(df)
# do do it for some names in a vector named 'col_names'
df[col_names] <- lapply(df[col_names] , factor)
Run Code Online (Sandbox Code Playgroud)
说明.所有数据帧都是列表,并且[使用多值参数的结果同样是列表,因此循环遍历列表是任务lapply.上面的赋值将创建一组列表,函数data.frame.[<-应该成功地重新插入到数据帧中,df
另一种策略是仅转换那些唯一项数小于某个标准的列,例如,比行数的日志少:
cols.to.factor <- sapply( df, function(col) length(unique(col)) < log10(length(col)) )
df[ cols.to.factor] <- lapply(df[ cols.to.factor] , factor)
Run Code Online (Sandbox Code Playgroud)
sbh*_*bha 20
您可以使用dplyr::mutate_if()将所有字符列或dplyr::mutate_at()选定的命名字符列转换为因子:
library(dplyr)
# all character columns to factor:
df <- mutate_if(df, is.character, as.factor)
# select character columns 'char1', 'char2', etc. to factor:
df <- mutate_at(df, vars(char1, char2), as.factor)
Run Code Online (Sandbox Code Playgroud)
Sam*_*rke 16
如果要在已经加载数据之后将data.frame中的所有字符变量更改为因子,可以这样做,将其命名为data.frame dat:
character_vars <- lapply(dat, class) == "character"
dat[, character_vars] <- lapply(dat[, character_vars], as.factor)
Run Code Online (Sandbox Code Playgroud)
这将创建一个向量,用于标识哪些列属于类character,然后应用于as.factor这些列.
样本数据:
dat <- data.frame(var1 = c("a", "b"),
var2 = c("hi", "low"),
var3 = c(0, 0.1),
stringsAsFactors = FALSE
)
Run Code Online (Sandbox Code Playgroud)
chr*_*lle 11
您可以使用的另一种简短方法是使用magrittr包中的pipe(%<>%).它将字符列mycolumn转换为一个因子.
library(magrittr)
mydf$mycolumn %<>% factor
Run Code Online (Sandbox Code Playgroud)
小智 5
我用一个函数来做。在这种情况下,我仅将字符变量转换为因数:
for (i in 1:ncol(data)){
if(is.character(data[,i])){
data[,i]=factor(data[,i])
}
}
Run Code Online (Sandbox Code Playgroud)