从 R 中的 chisq 输出中提取元素

问题描述

library(survey)

我正在使用调查包来生成两个分类变量间的 P 值和 Chisq。我想一次在许多变量上运行卡方并将数据提取到数据框中。

我有这样的数据。

df <- data.frame(sex = c('F','M',NA,'F','F'),happy = c('Y','Y','N','N'),married = c(1,1,1),pens = c(0,0),weight = c(1.12,0.55,1.1,0.6,0.23,0.66,0.67))

我运行以下代码来创建调查设计:

design <- svydesign(ids=~1,data=df,weights=~weight)

要找到性和笔的卡方:

svychisq(~sex+pens,design,statistic = "Chisq")

    Pearson's X^2: Rao & Scott adjustment

data:  svychisq(~sex + pens,statistic = "Chisq")
X-squared = 8,df = 1,p-value = 1.319e-08

我的实际数据集非常大,我想找到许多变量的chisq(在这种情况下是sex和happy)并将输出变成这样一个整洁的df:

Question  Group    Chisq  Pval
sex       pens     78     0.001
sex       married  45     0.100
happy     pens     34     0.3
happy     married  87     2.0

这是我目前所拥有的:

vector_vars <- c("sex","happy") 
myfun <- function(x){
  form <- reformulate(sprintf('interaction(%s)',x))
  all <- as.data.frame(svychisq(form + pens,statistic = "Chisq"))
  stat <- all$statistic # get the chi sq val
  p <- all$p.value  # get the p val
  cbind(as.data.frame(stat,p))
}


out_df <- do.call(rbind,lapply(vector_vars,myfun))

我收到此错误

  Error in terms(formula) : object 'pens' not found  

我认为我没有正确提取元素。任何建议表示赞赏。

解决方法

函数中的 reformulate 可以通过将 termlabels 指定为带有循环变量名称的 'pens' 向量来更改,然后将该公式传递给 svychisq,使用 {{ 1}} 将输出转换为 tidy 并将 tibble rbindlist 转换为单个 tibble

tibble
,

使用基础 R,您可以:

out_df <- do.call(rbind,lapply(vector_vars,function(x){with(svychisq(reformulate(termlabels = c('pens',x)),design,statistic = "Chisq"),data.frame(stat=statistic,p=p.value,row.names = x))}))
,

将您的 svychisq 分配给一个对象。 然后检查names() 并使用 test$p.value 获取 p.value 或从您需要的名称中进行选择 在你的情况test$statistic

test <- svychisq(~sex+pens,statistic = "Chisq")
names(test)
#test$p.value
test$statistic

# Output:
> test <- svychisq(~sex+pens,statistic = "Chisq")
> names(test)
[1] "statistic" "parameter" "p.value"   "method"    "data.name" "observed"  "expected"  "residuals" "stdres"   
> test$p.value
   X-squared 
1.319262e-08 

> test$statistic
X-squared 
        8