R -apply- convert many columns from numeric to factor

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.


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 

You can place your results back into a data frame which will recognize the factors:

df[,cols]<-data.frame(apply(df[,cols], 2, function(x){ as.factor(x)}))

Tags:

Class

R

Apply