在R语言中生成表格时如何保持评分量表的原始顺序?
The default alphabetical sorting happens because your question1 variable is probably stored as a character vector. To get the table in your desired Likert scale order, you need to convert it to a factor with custom levels defined in the sequence you want.
Here's the step-by-step solution:
- First, define your preferred scale order as a character vector:
scale_order <- c("strongly agree", "agree", "neutral", "disagree", "strongly disagree")
- Convert
question1to a factor using these levels. This tells R the exact order you want to use for this variable:
question1 <- factor(question1, levels = scale_order)
- Now run the
table()function again—it will respect your custom level order instead of sorting alphabetically:
table(question1)
This should produce the output you're looking for:
strongly agree agree neutral disagree strongly disagree 30 40 45 15 22
Why this works:
Factors in R have an explicit, user-definable order of levels. When you use table() on a factor, it uses this predefined order to arrange the output, rather than falling back to alphabetical sorting of character values.
If you don't want to modify the original question1 variable (e.g., you still need it as a character vector for other tasks), you can create a temporary factor instead:
temp_likert_factor <- factor(question1, levels = scale_order) table(temp_likert_factor)
This will give you the same correctly ordered table without altering your original data.
内容的提问来源于stack exchange,提问作者Yubin

