1

I have 77 numeric variables which are technically ordered factor variables. I know that I can do the below for changing the first column of data frame df into an ordered factor variable:

df[,1]<-as.ordered(df[,1])

But is there a quick way that I can turn the entire data frame of 77 variables into a data frame of ordered factor variables?

Thank you,

chico0913
  • 577
  • 4
  • 10
  • 22

2 Answers2

2

We can loop over the dataset columns with lapply, apply the function and assign it back to the original dataset

df[] <- lapply(df, as.ordered)

Or with dplyr

library(dplyr)
df <- df %>%
         mutate_all(as.ordered)
akrun
  • 874,273
  • 37
  • 540
  • 662
1

For such cases is for loop good and fast enough.

for (i in 1:ncol(df)) df[, i] <- as.factor(df[, i])

(Very likely - from my experience - faster than any lapply or any apply-family solution - because avoiding building lists which are very slow in R.)

For 1:ncol(df) you can also use seq_along(df).

Gwang-Jin Kim
  • 9,303
  • 17
  • 30