英文:
Reorder factor levels in table1 in R
问题
I am putting together a descriptive statistics table in R using the table1 project and noticed that regardless of how I order factor variables, the table1 function defaults to sorting these factor levels in alphabetical order. For example it sorts income categories in the order of "10k-20k, 20k-30k, etc..., Less than 20k" because L comes after numbers in alphabetical order. I would like for the "Less than 20k" variable to be the first row for income. There are other cases for this table where the variable is ordinal and thus alphabetical order may mess with the order that I'd like to see displayed. Does anyone know how to fix this?
I tried reordering the factors in the tidyverse, but table1 seems to default to alphabetical sorting for factor levels.
英文:
I am putting together a descriptive statistics table in R using the table1 project and noticed that regardless of how I order factor variables, the table1 function defaults to sorting these factor levels in alphabetical order. For example it sorts income categories in the order of "10k-20k, 20k-30k, etc..., Less than 20k" because L comes after numbers in alphabetical order. I would like for the "Less than 20k" variable to be the first row for income. There are other cases for this table where the variable is ordinal and thus alphabetical order may mess with the order that I'd like to see displayed. Does anyone know how to fix this?
I tried reordering the factors in the tidyverse, but table1 seems to default to alphabetical sorting for factor levels
答案1
得分: 2
你可以使用factor()
函数中的levels=
参数:
set.seed(42)
lbl <- c("Strongly Disagree", "Disagree", "No Opinion", "Agree", "Strongly Agree")
dta <- sample(lbl, 25, replace=TRUE)
dta.f1 <- factor(dta)
table(dta.f1)
# dta.f1
# Agree Disagree No Opinion Strongly Agree Strongly Disagree
# 5 6 2 5 7
dta.f2 <- factor(dta, levels=lbl)
table(dta.f2)
# dta.f2
# Strongly Disagree Disagree No Opinion Agree Strongly Agree
# 7 6 2 5 5
英文:
You use the levels=
argument in factor()
:
set.seed(42)
lbl <- c("Strongly Disagree", "Disagree", "No Opinion", "Agree", "Strongly Agree")
dta <- sample(lbl, 25, replace=TRUE)
dta.f1 <- factor(dta)
table(dta.f1)
# dta.f1
# Agree Disagree No Opinion Strongly Agree Strongly Disagree
# 5 6 2 5 7
dta.f2 <- factor(dta, levels=lbl)
table(dta.f2)
# dta.f2
# Strongly Disagree Disagree No Opinion Agree Strongly Agree
# 7 6 2 5 5
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论