Reputation: 647
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,
Upvotes: 1
Views: 893
Reputation: 9865
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)
.
Upvotes: 1
Reputation: 886948
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)
Upvotes: 2