簡體   English   中英

如何在R中的列表上制作列聯表

[英]How to make contingency table over a list in r

主要的曝光量是aff 我想獲取affvarlist所有變量的列聯表。 然后,我想使用這些列聯表進行卡方檢驗。 我的代碼如下:

name=names(data)
varlist=name[11:40]
models=lapply(varlist, function(x) {
          chisq.test(table(substitute(data$i,list(i = as.name(x))),data$aff))
 })
lapply(models, summary)

但是我有錯誤

Error in unique.default(x, nmax = nmax) : 
  unique() applies only to vectors

如何解決這個問題?

我認為您通過使用substitute等使事情變得過於復雜。 沒有你的數據,我會盡力與mtcars ,利用cyl作為暴露變量。

data <- mtcars
name <- names(data)
ev <- "cyl"
varlist <- name[ name != ev ]
models <- lapply(varlist, function(nm) {
  chisq.test(table(data[[nm]], data[[ev]]))
})
# Warning messages:
# 1: In chisq.test(table(data[[nm]], data[[ev]])) :
#   Chi-squared approximation may be incorrect

(因為我在測試中使用了不好的示例,所以這里有很多警告;在使用mtcars時可以忽略此警告,因為它實際上不是該測試的良好數據集。)

summaries <- lapply(models, summary)
str(summaries[1:2])
# List of 2
#  $ : 'summaryDefault' chr [1:9, 1:3] " 1" " 1" " 1" " 1" ...
#   ..- attr(*, "dimnames")=List of 2
#   .. ..$ : chr [1:9] "statistic" "parameter" "p.value" "method" ...
#   .. ..$ : chr [1:3] "Length" "Class" "Mode"
#  $ : 'summaryDefault' chr [1:9, 1:3] " 1" " 1" " 1" " 1" ...
#   ..- attr(*, "dimnames")=List of 2
#   .. ..$ : chr [1:9] "statistic" "parameter" "p.value" "method" ...
#   .. ..$ : chr [1:3] "Length" "Class" "Mode"

假設您的數據就像mtcars ,其中vsamgearcarb是分類變量,則可以這樣創建一個函數:

df_list_f <- function(x) chisq.test(table(df2$cyl, x))
df2 <- mtcars[,8:11] # df2 contains the columns vs, am, gear and carb
lapply(df2, df_list_f)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM