用平均值和标准差在R中生成交叉表 [英] Generate Cross-table in R with mean and SD

查看:136
本文介绍了用平均值和标准差在R中生成交叉表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的数据集,我需要为其生成多个交叉表.这些尤其是二维表,用于生成频率以及均值和标准差.

I have a large dataset for which I need to generate multiple cross-tables. These are particularly two dimensional tables to generate frequencies along with mean and SD.

举个例子,我有以下数据-

So give an example I have the below data -

City <- c("A","B","A","A","B","C","D","A","D","C")
Q1 <- c("Agree","Agree","Agree","Agree","Agree","Neither","Neither","Disagree","Agree","Agree")
df <- data.frame(City,Q1)

记住数据,我想生成一个平均值如下的交叉表-

Keeping the data in mind, I want to generate a cross-table with mean as below -

    City            
        A   B   C   D
Agree   3   2   1   1
Neither         1   1
Disagree    1           
Total   4   2   2   2
Mean    2.5 3   2.5 2.5

在生成平均值时,Agree的权重为3,Ngree的权重都不为2,Disagree的权重为1.在每一列和每一行之间都有网格线会很好.

When generating the mean, Agree is given a weight of 3, Neither is given a weight of 2 and Disagree is a given a weight of 1. The cross-table output should have the mean just below the Total column. It would be good to have gridlines between each column and row.

能否请您提出如何在R中实现这一目标?

Can you please suggest how to achieve this in R?

推荐答案

以下是使用addmargins的可能解决方案,它允许您将预定义函数传递给table结果

Here's a possible solution using addmargins which allows you to pass predefined functions to your table result

wm <- function(x) sum(x * c(3, 1, 2)) / sum(x)
addmargins(table(df[2:1]), 1, list(list(Total = sum, Mean = wm)))

#           City
# Q1           A   B   C   D
#   Agree    3.0 2.0 1.0 1.0
#   Disagree 1.0 0.0 0.0 0.0
#   Neither  0.0 0.0 1.0 1.0
#   Total    4.0 2.0 2.0 2.0
#   Mean     2.5 3.0 2.5 2.5

如果要使用SD,只需将, SD = sd添加到功能列表中

If you want SD to, you can simply add , SD = sd to the functions list

这篇关于用平均值和标准差在R中生成交叉表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆