我试图为数据集添加标签。标签始终按字母顺序排序,而不是按值排序。请帮帮我。 代码是:
sat.df<- data.frame(sapply(satdata, factor,
levels = c( 1, 2, 3, 4, 5, 9),
labels = c( "Not at all Satisfied", "Not satisfied", "Neural",
"Satisfied", "Very Satisfied", "Not Applicable")))
我得到的摘要结果是:
q1 Q6_a
Neural :116 Neural : 35
Not Applicable : 25 Not Applicable : 47
Not at all Satisfied: 13 Not at all Satisfied: 1
Not satisfied : 32 Not satisfied : 14
Satisfied :325 Satisfied :132
Very Satisfied :399 Very Satisfied :171
NA's : 6 NA's :516
我想知道是否有办法将它们从1重新排序到9。 非常感谢你!
答案 0 :(得分:2)
sapply
会简化为character
矩阵,会丢失因子级别顺序。您可以设置simplify = F
或使用lapply
代替。
# sample data (please include something like this
# in your question next time)
satdata = data.frame(q1 = 1:3, q2 = 3:5)
summary(data.frame(sapply(satdata, factor,
levels = c( 1, 2, 3, 4, 5, 9),
labels = c( "Not at all Satisfied", "Not satisfied", "Neural",
"Satisfied", "Very Satisfied", "Not Applicable"),
simplify = FALSE)))
summary(data.frame(lapply(satdata, factor,
levels = c( 1, 2, 3, 4, 5, 9),
labels = c( "Not at all Satisfied", "Not satisfied", "Neural",
"Satisfied", "Very Satisfied", "Not Applicable"))))
q1 q2
Not at all Satisfied:1 Not at all Satisfied:0
Not satisfied :1 Not satisfied :0
Neural :1 Neural :1
Satisfied :0 Satisfied :1
Very Satisfied :0 Very Satisfied :1
Not Applicable :0 Not Applicable :0