一次将多个列强制转换为因子 [英] Coerce multiple columns to factors at once
本文介绍了一次将多个列强制转换为因子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下示例数据框:
I have a sample data frame like below:
data <- data.frame(matrix(sample(1:40), 4, 10, dimnames = list(1:4, LETTERS[1:10])))
我想知道如何选择多个列并将它们一起转换为因子.我通常以 data$A = as.factor(data$A)
之类的方式进行操作.但是当数据框非常大并且包含很多列时,这种方式将非常耗时.有谁知道更好的方法吗?
I want to know how can I select multiple columns and convert them together to factors. I usually do it in the way like data$A = as.factor(data$A)
. But when the data frame is very large and contains lots of columns, this way will be very time consuming. Does anyone know of a better way to do it?
推荐答案
选择一些列强制转换为因子:
Choose some columns to coerce to factors:
cols <- c("A", "C", "D", "H")
使用 lapply()
强制和替换选定的列:
Use lapply()
to coerce and replace the chosen columns:
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"
这篇关于一次将多个列强制转换为因子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文