多重响应分析

2023-12-31

df1 <-
  data.frame(c("male", "female", "male"),
             c("1", "2", "3", "4", "5", "6"),
             seq(141, 170))

names(df1) = c("gender", "age", "height")

df1$age <- factor(
  df1$age,
  levels = c(1, 2, 3, 4, 5, 6),
  labels = c("16-24", "25-34", "35-44", "45-54", "55-64", "65+")
)

q1a = c(1, 0, 1, 0, 0, 1)
q1b = c(0, 0, 2, 2, 2, 0)
q1c = c(0, 0, 3, 3, 0, 3)
# 1,2 and 3 used to be compatible with existing datasets. 
# Could change all to 1 if necessary.

df2 <- data.frame(q1a = q1a, q1b = q1b, q1c = q1c)
df1 <- cbind(df1, df2)

rm(q1a, q1b, q1c, df2)

我希望在 R 中复制 SPSS 的多重响应问题的分析。

目前我正在使用这段代码:

#creating function for analysing questions with grouped data
multfreqtable <- function(a, b, c) {
  # number of respondents (for percent of cases)
  totrep = sum(a == 1 | b == 2 | c == 3)
  
  #creating frequency table
  table_a = data.frame("a", sum(a == 1))
  names(table_a) = c("question", "freq")
  table_b = data.frame("b", sum(b == 2))
  names(table_b) = c("question", "freq")
  table_c = data.frame("c", sum(c == 3))
  names(table_c) = c("question", "freq")
  table_question <- rbind(table_a, table_b, table_c)
  
  #remove individual question tables
  rm(table_a, table_b, table_c)
  
  #adding total
  total = as.data.frame("Total")
  totalsum = (sum(table_question$freq, na.rm = TRUE))
  totalrow = cbind(total, totalsum)
  names(totalrow) = c("question", "freq")
  table_question = rbind(table_question, totalrow)
  
  #adding percentage column to frequency table
  percentcalc = as.numeric(table_question$freq)
  percent = (percentcalc / totalsum) * 100
  table_question <- cbind(table_question, percent)
  
  #adding percent of cases column to frequency table
  poccalc = as.numeric(table_question$freq)
  percentofcases = (poccalc / totrep) * 100
  table_question <- cbind(table_question, percentofcases)
  
  #print percent of cases value
  total_respondents <<- data.frame(totrep)
  
  #remove all unnecessary data and values
  rm(
    total,
    totalsum,
    totalrow,
    b,
    c,
    percent,
    percentcalc,
    percentofcases,
    totrep,
    poccalc
  )
  
  return(table_question)
}

#calling function - must tie to data.frame using $ !!!
q1_frequency <- multfreqtable(df1$q1a, df1$q1b, df1$q1c)

#renaming percent of cases - This is very important while using current method
total_respondents_q1 <- total_respondents
rm(total_respondents)

生成此表的结果:

我正在寻找一种更有效的方法来执行此操作,如果存在或多或少的多项选择问题,理想情况下不需要编辑该函数。


您的功能实际上对于您需要做的事情来说太复杂了。我认为这样的功能应该可以工作并且更加灵活。

multfreqtable = function(data, question.prefix) {
  # Find the columns with the questions
  a = grep(question.prefix, names(data))
  # Find the total number of responses
  b = sum(data[, a] != 0)
  # Find the totals for each question
  d = colSums(data[, a] != 0)
  # Find the number of respondents
  e = sum(rowSums(data[,a]) !=0)
  # d + b as a vector. This is your overfall frequency 
  f = as.numeric(c(d, b))
  data.frame(question = c(names(d), "Total"),
             freq = f,
             percent = (f/b)*100,
             percentofcases = (f/e)*100 )
}

在示例数据集中添加另一个问题:

set.seed(1); df1$q2a = sample(c(0, 1), 30, replace=T)
set.seed(2); df1$q2b = sample(c(0, 2), 30, replace=T)
set.seed(3); df1$q2c = sample(c(0, 3), 30, replace=T)

为“q1”响应制作一个表格:

> multfreqtable(df1, "q1")
  question freq   percent percentofcases
1      q1a   15  33.33333             60
2      q1b   15  33.33333             60
3      q1c   15  33.33333             60
4    Total   45 100.00000            180

为“q2”响应制作一个表格:

> multfreqtable(df1, "q2")
  question freq   percent percentofcases
1      q2a   14  31.11111       53.84615
2      q2b   13  28.88889       50.00000
3      q2c   18  40.00000       69.23077
4    Total   45 100.00000      173.07692

多个问题的表格

这是该函数的修改版本,它允许您一次为多个问题创建表列表:

multfreqtable = function(data, question.prefix) {
  z = length(question.prefix)
  temp = vector("list", z)

  for (i in 1:z) {
    a = grep(question.prefix[i], names(data))
    b = sum(data[, a] != 0)
    d = colSums(data[, a] != 0)
    e = sum(rowSums(data[,a]) !=0)
    f = as.numeric(c(d, b))
    temp[[i]] = data.frame(question = c(sub(question.prefix[i], 
                                            "", names(d)), "Total"),
                           freq = f,
                           percent = (f/b)*100,
                           percentofcases = (f/e)*100 )
    names(temp)[i] = question.prefix[i]
  }
  temp
}

例子:

> multfreqtable(df1, "q1")
$q1
  question freq   percent percentofcases
1        a   15  33.33333             60
2        b   15  33.33333             60
3        c   15  33.33333             60
4    Total   45 100.00000            180

> test1 = multfreqtable(df1, c("q1", "q2"))
> test1
$q1
  question freq   percent percentofcases
1        a   15  33.33333             60
2        b   15  33.33333             60
3        c   15  33.33333             60
4    Total   45 100.00000            180

$q2
  question freq   percent percentofcases
1        a   14  31.11111       53.84615
2        b   13  28.88889       50.00000
3        c   18  40.00000       69.23077
4    Total   45 100.00000      173.07692

> test1$q1
  question freq   percent percentofcases
1        a   15  33.33333             60
2        b   15  33.33333             60
3        c   15  33.33333             60
4    Total   45 100.00000            180
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

多重响应分析 的相关文章

  • 如何让 print() 将参数传递给 R 中用户定义的打印方法?

    我在 R 中定义了一个 S3 类 它需要自己的打印方法 当我创建这些对象的列表并打印它时 R 按其应有的方式对列表中的每个元素使用我的打印方法 我想对打印方法实际显示的数量进行一些控制 因此 我的类的 print 方法需要一些额外的参数 但
  • 将循环转换为并行计算的函数

    我正在使用 R 编程语言 我遇到这个问题 我试图找出两个 shapefile 之间的成对交集 即第一个 shapefile 中的每个多边形与第二个 shapefile 中的所有多边形相交的百分比 我想我找到了解决这个问题的基本方法 Load
  • decompose() 的周期太少[关闭]

    很难说出这里问的是什么 这个问题是含糊的 模糊的 不完整的 过于宽泛的或修辞性的 无法以目前的形式得到合理的回答 如需帮助澄清此问题以便重新打开 访问帮助中心 help reopen questions 错误看起来像这样 decompose
  • 将命名参数列表传递给函数?

    我想编写一个小函数来从适当的分布生成样本 例如 makeSample lt function n dist params values lt makeSample 100 unif list min 0 max 10 values lt m
  • 基于服务器中的条件逻辑呈现闪亮的用户输入

    我正在尝试设置一个闪亮的导航栏面板页面 其中用户控制我根据一组单选按钮中所做的初始选择来显示更改 我直接在 ui 中渲染单选按钮 然后在 Server r 中的 观察到的 逻辑控制结构内构建条件控件 弹出错误是因为我的初始 if 语句计算结
  • 返回数据帧 R 中的下一行

    我有一个看起来像这样的数据框 kind datetime book 2016 04 23 04 23 00 pen 2016 04 23 04 30 00 toy 2016 04 23 06 45 00 我想为数据集中的每一行返回下一行的日
  • ggplot2可以在一个图例中分别控制点大小和线大小(线宽)吗?

    一个使用的例子ggplot2绘制数据点组和连接每组均值的线 并使用相同的映射aes for shape并为linetype p lt ggplot mtcars aes gear mpg shape factor cyl linetype
  • 如何在R中删除重复项

    我有一个非常大的数据集 如下所示 df lt data frame school c a a a b b c c c year c 3 3 1 4 2 4 3 1 GPA c 4 4 4 3 3 3 2 2 school year GPA
  • 如何在for循环中引用变量?

    我正在循环访问不同的 data tables 和 data table 中的变量 但我在引用内部变量时遇到问题for loop dt1 lt data table a1 c 1 2 3 a2 c 4 5 2 dt2 lt data tabl
  • 如何从 Fortran 调用 R 函数?

    根据http gallery rcpp org articles r function from c http gallery rcpp org articles r function from c Rcpp 允许用户从 C 调用 R 函数
  • 我无法下载 R 中的 reshape2 包 [关闭]

    Closed 这个问题是无法重现或由拼写错误引起 help closed questions 目前不接受答案 我在尝试安装 R 包时收到此响应 gt installed packages reshape2 Package LibPath V
  • 使用 pracma::findpeaks 识别持续峰值

    我的语法有问题peakpat内的选项findpeaks内的函数pramcaR 包 v 2 1 1 我使用的是 R 3 4 3 x64 Windows 我希望该函数能够识别可能有两个重复值的峰值 并且我相信该选项peakpat这就是我能做到的
  • 时间戳半小时窗口内字段的平均值

    我的数据框有列名Timestamp es看起来像 Timestamp es 2015 04 01 09 07 42 31 2015 04 01 09 08 01 29 5 2015 04 01 09 15 03 18 5 2015 04 0
  • 如何使用 usmap 标记数字而不是名称?

    我知道 usmap 有一个选项label in plot usmap 我想标记一些数字 而不是状态名称 我想 usmap 中应该有与州质心坐标相关的数据 但我不知道如何找到它 如果我能得到 坐标然后我可以用它来标记数字geom text 这
  • Dendextend:关于如何根据定义的组为树状图的标签着色

    我正在尝试使用一个名为 dendextend 的很棒的 R 包来绘制树状图并根据一组先前定义的组为其分支和标签着色 我已阅读您在 Stack Overflow 中的答案以及 dendextend vignette 的常见问题解答 但我仍然不
  • 将每列的值乘以 R 中另一个 data.frame 中的权重

    我有两个data frames df and weights 代码如下 df看起来像这样 id a b d EE f 1 this 0 23421153 0 02324956 0 5457353 0 73068586 0 5642554 2
  • r 中训练和测试数据的最小最大缩放/归一化

    我正在创建一个函数 它将训练集和测试集作为其参数 最小 最大缩放 标准化并返回训练集并使用这些same最小值和最小 最大范围的值 标准化并返回测试集 到目前为止 这是我想出的功能 min max scaling lt function tr
  • 在 R 中使用 lapply 绘制多个数据帧

    我正在尝试使用 lapply 函数绘制多个数据帧 每个数据帧一个图 但是尽管有关此主题的所有帖子我都找不到答案 因为我不断收到错误 图的输出列表为空 我的数据结构如下 df1 lt mtcars gt group by cyl gt tal
  • 使用 Shiny 发布平行坐标图表时出现“错误:路径[1]="”:没有这样的文件或目录”

    我有一个似乎很常见但我还没有找到解决方案的问题 当尝试使用 rCharts Parcoords 发布 Web 应用程序时 出现以下错误 错误 路径 1 没有这样的文件或目录 奇怪的是 该应用程序在我的笔记本电脑上运行得很好 下面是我正在使用
  • 更改闪亮 R 中的默认浏览器

    我在 RStudio 中使用 01 hello 虽然在 IE 中默认打开程序时它不会显示直方图 但即使在 Chrome 中 滑块也不起作用 我无法滑动条形图并看到直方图中的变化 如何更改 R 中的默认浏览器 以便闪亮启动 Chrome 而不

随机推荐