【问题标题】:Creating a list of contingency tables from variables in a data frame using for loop and if statement?使用for循环和if语句从数据框中的变量创建列联表列表?
【发布时间】:2018-09-19 10:46:15
【问题描述】:

数据框示例:

 WasAdmitted concldur ArrivalDayWdWe IMDQuintile log_depdur
           1      130        Weekend          Q1   5.480639
           1      177        Weekday          Q1   5.370638
           0      125        Weekday          Q2   4.828314
           1      102        Weekday          Q5   5.220356
           1      203        Weekday          Q4   5.402677
           0      168        Weekday          Q2   5.123964

sample <- structure(list(WasAdmitted = c(1L, 1L, 0L, 1L, 1L, 0L), concldur = c(130L, 
177L, 125L, 102L, 203L, 168L), ArrivalDayWdWe = structure(c(2L, 
1L, 1L, 1L, 1L, 1L), .Label = c("Weekday", "Weekend"), class = "factor"), 
    IMDQuintile = structure(c(1L, 1L, 2L, 5L, 4L, 2L), .Label = c("Q1", 
    "Q2", "Q3", "Q4", "Q5"), class = "factor"), log_depdur = c(5.48063892334199, 
    5.37063802812766, 4.8283137373023, 5.22035582507832, 5.40267738187228, 
    5.12396397940326)), class = "data.frame")

我有WasAdmitted 作为我感兴趣的二进制因变量。我想针对我的数据框中的所有其他变量(类型因子、整数或字符)生成一个WasAdmitted 的列联表列表,以生成列联表列表。所以我排除了数值变量。

首先,我创建了这个:

for (i in sample){
if (typeof(i) %in% c("integer", "factor", "chr"))
  return(table(sample$i, sample$WasAdmitted))
}

但是我不确定如何从这里开始。

【问题讨论】:

    标签: r list for-loop if-statement apply


    【解决方案1】:

    您可以使用lapply 在获取非数字列后生成表格。

    inx <- sapply(sample, inherits, "numeric")
    contg <- lapply(sample[!inx][-1], table, sample[!inx][[1]])
    
    contg[1]
    #$concldur
    #     
    #      0 1
    #  102 0 1
    #  125 1 0
    #  130 0 1
    #  168 1 0
    #  177 0 1
    #  203 0 1
    

    编辑。

    如果你想用这个结果来计算一些东西,你可以*apply你选择的函数给它的每个成员。

    例如,为了计算每个表的卡方检验:

    chiq_list <- lapply(contg, chisq.test)
    

    这与在结果 contg 的 3 个成员中的每一个上运行一个 chisq.test 相同。

    length(contg)
    #[1] 3
    
    chisq.test(contg [[1]])
    chisq.test(contg [[2]])
    chisq.test(contg [[3]])
    

    然后您可以从测试结果列表中提取您想要的内容。

    以下是提取测试统计数据的方法。

    sapply(chiq_list, '[[', 'statistic')
    #      concldur.X-squared ArrivalDayWdWe.X-squared 
    #            6.000000e+00             4.252453e-32 
    #   IMDQuintile.X-squared 
    #                     NaN
    

    或 p 值。

    sapply(chiq_list, '[[', 'p.value')
    # concldur ArrivalDayWdWe    IMDQuintile 
    #0.3062189      1.0000000            NaN
    

    【讨论】:

    • 我可以使用chisq.test 做类似的事情吗?所以我想创建一个列表,列出WasAdmittedconcldurIMDQuntile 等的所有 chisq.test 结果,但不是像log_depdur 这样的数字向量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 2014-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多