ordering n factor variables in data.frame(r) [duplicate]

强颜欢笑 提交于 2021-01-29 03:07:18

问题


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?


回答1:


We can use tidyverse

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


来源:https://stackoverflow.com/questions/42224732/ordering-n-factor-variables-in-data-framer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!