如何将数据框中的调查答案转换为数字以求平均结果

out*_*tis 0 r

我有一个包含调查结果的数据框,如下所示:

          Q1         Q2       Q3
1      Agree No opinion Disagree
2 No opinion No opinion Disagree
3      Agree            Disagree
Run Code Online (Sandbox Code Playgroud)

如何将调查回复转换为数字,以便获得每个问题的平均回复?我可以使用 gsub 为每列中的每个文本答案替换数值,但必须有更好的方法。

> str(x)
'data.frame':   3 obs. of  3 variables:
 $ Q1: Factor w/ 2 levels "Agree","No opinion": 1 2 1
 $ Q2: Factor w/ 2 levels "","No opinion": 2 2 1
 $ Q3: Factor w/ 1 level "Disagree": 1 1 1
Run Code Online (Sandbox Code Playgroud)

The*_*ras 5

好的,现在很清楚了。

我会将每一列转换为字符,然后转换为因子(具有公共级别),然后转换为整数:

sapply(data, function(x) as.integer(factor(as.character(x), levels=c("Agree", "No opinion", "Disagree"))))
Run Code Online (Sandbox Code Playgroud)