3 回答
TA贡献2011条经验 获得超2个赞
选择一些列以强制考虑因素:
cols <- c("A", "C", "D", "H")
使用lapply()强迫和更换所选列:
data[cols] <- lapply(data[cols], factor) ## as.factor() could also be used
检查结果:
sapply(data, class)
# A B C D E F G
# "factor" "integer" "factor" "factor" "integer" "integer" "integer"
# H I J
# "factor" "integer" "integer"
TA贡献1799条经验 获得超8个赞
最近的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
- 3 回答
- 0 关注
- 949 浏览
添加回答
举报