R -apply - convert many columns from number to number

I need to convert many columns that are numeric by type of factors. Example table:

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

I tried applying:

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?

+4
source share
4 answers

Try

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

The problem is that it apply()tries to associate the results with a matrix, which leads to forcing the columns to a character:

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

On the contrary, it lapply()works with list items.

+6
source

Updated November 9, 2017

purrr / purrrlyr are still under development

Like Ben, 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 
+4

, :

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

+3
source

Another option, with purrrand dplyr, perhaps, is slightly more readable than the basic ones, and stores data in a data frame:

Here is the data:

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

str(df)
'data.frame':   10 obs. of  3 variables:
 $ A: int  1 2 3 4 5 6 7 8 9 10
 $ B: int  2 3 4 5 6 7 8 9 10 11
 $ C: int  3 4 5 6 7 8 9 10 11 12

We can easily work with all columns with dmap:

library(purrr)
library(dplyr)

# all cols to factor
dmap(df, as.factor)

Source: local data frame [10 x 3]

        A      B      C
   (fctr) (fctr) (fctr)
1       1      2      3
2       2      3      4
3       3      4      5
4       4      5      6
5       5      6      7
6       6      7      8
7       7      8      9
8       8      9     10
9       9     10     11
10     10     11     12

And similarly, use dmapfor a subset of columns, using selectfrom dplyr:

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

df[,cols] <- 
  df %>% 
  select(one_of(cols)) %>% 
  dmap(as.factor)

To get the desired result:

str(df)
'data.frame':   10 obs. of  3 variables:
 $ A: Factor w/ 10 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10
 $ B: Factor w/ 10 levels "2","3","4","5",..: 1 2 3 4 5 6 7 8 9 10
 $ C: int  3 4 5 6 7 8 9 10 11 12
+1
source

Source: https://habr.com/ru/post/1618828/


All Articles