Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R -apply- convert many columns from numeric to factor

Tags:

class

r

apply

I need to convert many columns that are numeric to factor type. An example table:

df <- data.frame(A=1:10, B=2:11, C=3:12)

I tried with apply:

cols<-c('A', 'B')
df[,cols]<-apply(df[,cols], 2, function(x){ as.factor(x)});

But the result is a character class.

> class(df$A)
[1] "character"

How can I do this without doing as.factor for each column?

like image 327
GabyLP Avatar asked Dec 07 '15 00:12

GabyLP


2 Answers

Try

df[,cols] <- lapply(df[,cols],as.factor)

The problem is that apply() tries to bind the results into a matrix, which results in coercing the columns to character:

class(apply(df[,cols], 2, as.factor))  ## matrix
class(as.factor(df[,1]))  ## factor

In contrast, lapply() operates on elements of lists.

like image 117
Ben Bolker Avatar answered Sep 27 '22 23:09

Ben Bolker


Updated Nov 9, 2017

purrr / purrrlyr are still in development

Similar to Ben's, but using purrrlyr::dmap_at:

library(purrrlyr)

df <- data.frame(A=1:10, B=2:11, C=3:12)

# selected cols to factor
cols <- c('A', 'B')

(dmap_at(df, factor, .at = cols))

A        B       C
<fctr>   <fctr>  <int>
1        2       3      
2        3       4      
3        4       5      
4        5       6      
5        6       7      
6        7       8      
7        8       9      
8        9       10     
9        10      11     
10       11      12 
like image 26
Tanya Murphy Avatar answered Sep 27 '22 23:09

Tanya Murphy