【问题标题】:How to convert survey answers in data frame to numbers in order to average results如何将数据框中的调查答案转换为数字以平均结果
【发布时间】:2013-03-12 21:48:03
【问题描述】:

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

          Q1         Q2       Q3
1      Agree No opinion Disagree
2 No opinion No opinion Disagree
3      Agree            Disagree

如何将调查回复转换为数字,以便获得每个问题的平均回复?我可以使用 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

【问题讨论】:

  • sapply(data, as.integer) 怎么样?
  • @TheodoreLytras 这对他们的数据结构做了很多假设。因素与性格,即使是因素,我们也不知道等级的顺序。
  • @outis 为什么不在这里使用table?
  • @agstudy 因为显然他们认为如果我同意某事而你不同意,作为一个群体,我们没有意见。 ;)
  • 通过dput(head())分享您的数据或向我们展示str()的输出。

标签: r


【解决方案1】:

好的,现在很清楚了。

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

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

【讨论】:

  • 或者,使用 有序因子
【解决方案2】:

我一定误解了你想要什么,但既然你在 data.frame 中有分类变量,你不能只使用 summary 吗?

#Example
q1 <- sample( c("Agree" , "No opinion" ) , 10 , replace = TRUE )
q2 <- sample( c(" " , "No opinion" ) , 10 , replace = TRUE )
q3 <- sample( c("Agree" , "Disagree" ) , 10 , replace = TRUE )

x <- data.frame( q1 , q2 , q3 )

summary(x)
  q1             q2           q3   
  Agree     :4   ,         :4   Agree   :5  
  No opinion:6   No opinion:6   Disagree:5  

【讨论】:

    猜你喜欢
    • 2022-01-08
    • 2020-05-20
    • 2020-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    相关资源
    最近更新 更多