【问题标题】:Generate Cross-table in R with mean and SD在 R 中生成具有均值和 SD 的交叉表
【发布时间】:2017-03-09 04:47:19
【问题描述】:

我有一个大型数据集,需要为其生成多个交叉表。这些特别是用于生成频率以及平均值和 SD 的二维表。

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

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)

牢记数据,我想生成一个交叉表,其均值如下 -

    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,既定的权重为 2,Disagree 的权重为 1。交叉表输出的平均值应刚好低于 Total 列。在每列和每行之间有网格线会很好。

您能否建议如何在 R 中实现这一点?

【问题讨论】:

    标签: r dataset mean crosstab


    【解决方案1】:

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

    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 添加到函数列表中

    【讨论】:

    • 谢谢大卫!!知道如何添加网格线以更好地查看输出吗?
    【解决方案2】:

    这里有一个解决方案:

    x <- table(df$Q1, df$City) #building basic crosstab
    #assigning weights to vector
    weights <- c("Agree" = 3, "Disagree" = 1, "Neither" = 2)
    #getting weighted mean
    weightedmean <- apply(x, 2, function(x) {sum(x * weights)/sum(x)})
    #building out table
    x <- rbind(x,
               apply(x, 2, sum), #row sums
               weightedmean)
    rownames(x)[4:5] <- c("Total", "Mean")
    

    【讨论】:

      猜你喜欢
      • 2018-06-23
      • 1970-01-01
      • 2013-09-25
      • 1970-01-01
      • 2014-06-10
      • 1970-01-01
      • 2011-06-15
      相关资源
      最近更新 更多