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)
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
source
share