R环境下如何将调查问卷有序回答转为数值以开展单因素ANOVA分析
R语言问卷有序选项转数值操作步骤
假设你的数据集名称为survey_df,待转换的问卷回答列名为q1_importance,可选择以下两种方法操作:
方法1:命名向量映射法(推荐,容错性高)
直接定义选项和数值的对应关系,匹配错误的值会返回NA方便排查异常:
# 1. 定义映射规则,键名需要和你数据中的选项文本完全一致(包含括号、空格等符号) level_map <- c( "Extremely important(极其重要)" = 5, "Very important(非常重要)" = 4, "Moderately important(中等重要)" = 3, "Slightly important(稍微重要)" = 2, "Not at all(完全不重要)" = 1 ) # 2. 生成新的数值列 survey_df$importance_score <- level_map[survey_df$q1_importance]
方法2:有序因子转换法(适合需保留有序变量属性的场景)
如果后续还要做有序回归等分析,可先将列转为有序因子再转数值:
# 1. 按重要程度从低到高定义因子水平顺序 survey_df$q1_importance <- factor( survey_df$q1_importance, levels = c( "Not at all(完全不重要)", "Slightly important(稍微重要)", "Moderately important(中等重要)", "Very important(非常重要)", "Extremely important(极其重要)" ), ordered = TRUE ) # 2. 转为数值,自动按因子顺序赋值1-5 survey_df$importance_score <- as.numeric(survey_df$q1_importance)
验证转换结果
转换完成后执行以下代码核对对应关系,避免匹配错误:
table(survey_df$q1_importance, survey_df$importance_score)
核对无误后即可使用importance_score列进行ANOVA检验、均值计算等操作。
内容的提问来源于stack exchange,提问作者Vouvouzella
相关产品推荐
相关产品推荐

