在data.frame(r)中排序n个因子变量

时间:2017-02-14 11:16:36

标签: r dataframe

假设我有6列数据框(所有这些都是无序因素)。

          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>

我想将第2-6列作为有序因子变量。 我知道如何为每个变量分别执行此操作:df_new$TC026Q01NA <- as.ordered(df_new$TC026Q01NA)

但是如何在一(2)行代码中为所有变量执行此操作?

1 个答案:

答案 0 :(得分:1)

我们可以使用tidyverse

library(tidyverse)
df_new %>%
       mutate_at(2:6, as.ordered)