一次将多列强制转换为因子

我有一个示例数据框,如下所示:


data <- data.frame(matrix(sample(1:40), 4, 10, dimnames = list(1:4, LETTERS[1:10])))

我想知道如何选择多个列并将它们一起转换为因子。我通常会这样做data$A = as.factor(data$A)。但是,当数据帧很大且包含许多列时,这种方式将非常耗时。有谁知道更好的方法吗?


长风秋雁
浏览 873回答 3
3回答

森林海

选择一些列以强制考虑因素:cols <- c("A", "C", "D", "H")使用lapply()强迫和更换所选列:data[cols] <- lapply(data[cols], factor)&nbsp; ## as.factor() could also be used检查结果:sapply(data, class)#&nbsp; &nbsp; &nbsp; &nbsp; A&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;B&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;C&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;D&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;E&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;F&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;G&nbsp;# "factor" "integer"&nbsp; "factor"&nbsp; "factor" "integer" "integer" "integer"&nbsp;#&nbsp; &nbsp; &nbsp; &nbsp; H&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;I&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;J&nbsp;# "factor" "integer" "integer"&nbsp;

守着星空守着你

最近的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)&nbsp;$ A: Factor w/ 4 levels "5","17","18",..: 2 1 4 3&nbsp; &nbsp;&nbsp;$ B: int&nbsp; 36 35 2 26&nbsp;$ C: Factor w/ 4 levels "22","31","32",..: 1 2 4 3&nbsp;$ D: Factor w/ 4 levels "1","9","16","39": 3 4 1 2&nbsp;$ E: int&nbsp; 3 14 30 38&nbsp;$ F: int&nbsp; 27 15 28 37&nbsp;$ G: int&nbsp; 19 11 6 21&nbsp;$ H: Factor w/ 4 levels "7","12","20",..: 1 3 4 2&nbsp;$ I: int&nbsp; 23 24 13 8&nbsp;$ J: int&nbsp; 10 25 4 33
打开App,查看更多内容
随时随地看视频慕课网APP