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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With