The result of apply is a vector or an array or a list of values (see ?apply ).
For your problem, you should use lapply instead:
data(iris) iris[, 2:3] <- lapply(iris[, 2:3], as.factor) str(iris) 'data.frame': 150 obs. of 5 variables: $ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ... $ Sepal.Width : Factor w/ 23 levels "2","2.2","2.3",..: 15 10 12 11 16 19 14 14 9 11 ... $ Petal.Length: Factor w/ 43 levels "1","1.1","1.2",..: 5 5 4 6 5 8 5 6 5 6 ... $ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ... $ Species : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
Note that this is one place where lapply will be much faster than the for loop. In general, the loop and lapply will have similar characteristics, but the <-.data.frame is very slow. Using lapply , you avoid the <- operation at each iteration and replace it with one purpose. It is much faster.
source share