首页 > 解决方案 > 使用 R 中的函数查找 chi 统计信息

问题描述

我正在尝试创建一个函数以避免重新输入,但它不起作用,任何帮助将不胜感激,

library(descr)

mtcars$carb <- factor(mtcars$carb)
mtcars$gear <- factor(mtcars$gear)
CrossTable(mtcars$carb, mtcars$gear, expected=F, prop.r=T, prop.c=T, prop.t=T, prop.chisq=F, chisq = T)

到目前为止我的尝试:

a <- function(df,vec1,vec2){CrossTable(df$vec1, df$vec2, expected=F, prop.r=T, prop.c=T, prop.t=T, prop.chisq=F, chisq = T)}
a(mtcars,carb,gear)

标签: r

解决方案


放置未引用的参数需要使用非标准评估。这不是在R. 我建议您将参数作为列名

a <- function(df,col1,col2){CrossTable(df[,col1], df[,col2], expected=F, prop.r=T, prop.c=T, prop.t=T, prop.chisq=F, chisq = T)}

你的电话将是

a(mtcars,"carb","gear")


   Cell Contents 
|-------------------------|
|                       N | 
|           N / Row Total | 
|           N / Col Total | 
|         N / Table Total | 
|-------------------------|

===========================================
              df[, col2]
df[, col1]        3       4       5   Total
-------------------------------------------
1                 3       4       0       7
              0.429   0.571   0.000   0.219
              0.200   0.333   0.000        
              0.094   0.125   0.000        
-------------------------------------------
2                 4       4       2      10
              0.400   0.400   0.200   0.312
              0.267   0.333   0.400        
              0.125   0.125   0.062        
-------------------------------------------
3                 3       0       0       3
              1.000   0.000   0.000   0.094
              0.200   0.000   0.000        
              0.094   0.000   0.000        
-------------------------------------------
4                 5       4       1      10
              0.500   0.400   0.100   0.312
              0.333   0.333   0.200        
              0.156   0.125   0.031        
-------------------------------------------
6                 0       0       1       1
              0.000   0.000   1.000   0.031
              0.000   0.000   0.200        
              0.000   0.000   0.031        
-------------------------------------------
8                 0       0       1       1
              0.000   0.000   1.000   0.031
              0.000   0.000   0.200        
              0.000   0.000   0.031        
-------------------------------------------
Total            15      12       5      32
              0.469   0.375   0.156        
===========================================

Statistics for All Table Factors

Pearson's Chi-squared test 
------------------------------------------------------------
Chi^2 = 16.5181      d.f. = 10      p = 0.0857 

Warning message:
In chisq.test(tab, correct = FALSE, ...) :
  Chi-squared approximation may be incorrect

推荐阅读