R 中的加权表函数问题

问题描述

我有以下数据集(示例)

head(LK)

      Weight question result
15 0.9633132       x1    Yes
16 1.0327943       x1    Yes
19 1.0002033       x1    Yes
20 0.9438802       x1    Yes
24 0.8067644       x1     No
49 0.8951687       x1     No

当我将 wtd.table 函数用于单向表时,它运行良好

wtd.table(LK$result,weights=LK$Weight)

$x
[1] "No"  "Yes"

$sum.of.weights
[1]  747.2105 1996.9381

但是,当我尝试将其用于双向表时 - 我收到此错误

wtd.table(LK$result,LK$question,weights=LK$Weight)

Error in match.arg(type) : 'arg' must be NULL or a character vector

我见过使用这种语法的双向加权表的例子,所以不确定问题是什么。任何帮助表示赞赏。

解决方法

如果你只对权重和计数的总和感兴趣,但不需要将结果作为“表格”,你可以试试这个

library(tidyverse)

data <- tribble(
  ~Weight,~question,~result,0.9633132,"x1","Yes",1.0327943,1.0002033,0.9438802,0.8067644,"No",0.8951687,"No"
)
data
#> # A tibble: 6 x 3
#>   Weight question result
#>    <dbl> <chr>    <chr> 
#> 1  0.963 x1       Yes   
#> 2  1.03  x1       Yes   
#> 3  1.00  x1       Yes   
#> 4  0.944 x1       Yes   
#> 5  0.807 x1       No    
#> 6  0.895 x1       No


data %>% 
  group_by(question,result) %>% 
  summarise(n = n(),weight = sum(Weight))
#> `summarise()` has grouped output by 'question'. You can override using the `.groups` argument.
#> # A tibble: 2 x 4
#> # Groups:   question [1]
#>   question result     n weight
#>   <chr>    <chr>  <int>  <dbl>
#> 1 x1       No         2   1.70
#> 2 x1       Yes        4   3.94

reprex package (v1.0.0) 于 2021 年 3 月 12 日创建