1

Suppose I have data frame with 6 columns(all of them are unordered factors).

          teacher$TC001Q01NA        TC026Q01NA        TC026Q02NA        TC026Q04NA        TC026Q05NA        TC026Q06NA
1                    <NA>              <NA>              <NA>              <NA>              <NA>              <NA>
2                  Female    Strongly agree    Strongly agree Strongly disagree    Strongly agree Strongly disagree
3                    Male             Agree             Agree          Disagree             Agree          Disagree
4                  Female             Agree             Agree          Disagree             Agree             Agree
5                  Female             Agree             Agree Strongly disagree    Strongly agree Strongly disagree
6                    <NA>              <NA>              <NA>              <NA>              <NA>              <NA>
7                    <NA>              <NA>              <NA>              <NA>              <NA>              <NA>
8                  Female    Strongly agree             Agree Strongly disagree             Agree             Agree
9                    <NA>              <NA>              <NA>              <NA>              <NA>              <NA>
10                   <NA>              <NA>              <NA>              <NA>              <NA>              <NA>

I want to make columns 2-6 as ordered factor variables. I know how to do it separately for each variable: df_new$TC026Q01NA <- as.ordered(df_new$TC026Q01NA)

But how can I do this for all variables in one(two) line of code?

Daniel Yefimov
  • 860
  • 1
  • 10
  • 24
  • 3
    `lapply` will be your friend, I guess – talat Feb 14 '17 at 11:17
  • 1
    We can do `df_new[2:6] <- lapply(df_new[2:6], function(x) as.ordered(x))` – akrun Feb 14 '17 at 11:17
  • @akrun thank you for comment! Can you explain please, why does your code keep df_new as data.frame, but the code lapply(df_new[2:6], as.ordered) transforms it into the list? – Daniel Yefimov Feb 14 '17 at 11:24
  • 1
    The `[]` makes sure the structure on the lhs of `<-` is restored and `data.frame` is a `list` with equal number of elements – akrun Feb 14 '17 at 11:27

1 Answers1

1

We can use tidyverse

library(tidyverse)
df_new %>%
       mutate_at(2:6, as.ordered)
akrun
  • 874,273
  • 37
  • 540
  • 662