选择并将多个列转换为因素 [英] Select and convert multiple columns to factors

查看:147
本文介绍了选择并将多个列转换为因素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个样本数据框架,如下所示:

  data<  -  data.frame(matrix(sample(sample) 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)
#ABCDEFG
#factor 整数因子因子整数整数整数
#HIJ
#因子整数整数
/ pre>

I have a sample data frame like below:

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

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 if there any smart way to do it?

解决方案

Choose some columns to coerce to factors:

cols <- c("A", "C", "D", "H")

Use lapply() to coerce and replace the chosen columns:

data[cols] <- lapply(data[cols], factor)

Check the result:

sapply(data, class)
#        A         B         C         D         E         F         G 
# "factor" "integer"  "factor"  "factor" "integer" "integer" "integer" 
#        H         I         J 
# "factor" "integer" "integer" 

这篇关于选择并将多个列转换为因素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆