在 R 中使用 lapply 进行费舍尔精确检验时如何编辑输出中的数据名称?

How to edit data name in output when using lapply for fisher's exact test in R?

我正在尝试 运行 使用 lapply 对我的数据进行一系列 Fisher 精确检验,想知道是否可以在输出中指定数据名称。

这是我当前的代码:

vars <- c('xvar1', 'xvar2', 'xvar3')
lapply(vars, function(i) {fisher.test(dataframe[[i]], dataframe$yvar)})

这会产生我正在寻找的输出,但输出中的数据名称是“dataframe[[i]] and dataframe$yvar”。有没有办法让它变成“dataframe$xvar1 和 dataframe$yvar”?

我知道当 运行使用 ctables 计算卡方时,您可以使用 dnn 参数(下面的示例)来执行此操作,但尚未找到适用于费雪检验的等效参数。

ctables <- lapply(vars, function(i) {ctable(dataframe[[i]], dataframe$yvar, chisq=T, useNA='no', dnn=c(i,'yvar'))})

谢谢!

我不确定您的目标是什么。最有可能的是,您想从 Fisher 测试结果对象中提取结果(即 p-values)并将它们作为列表或数据框使用。

要做到这一点,请查看帮助:?fisher.test。如果向下滚动到值部分,您会看到它实际上是 returns 一个列表。虽然它有一个特殊的 class 使其以特殊方式打印出来,但它仍然是一个列表,我们可以像在任何其他列表中一样按名称访问列表元素。

x <- fisher.test(iris$Petal.Length, iris$Sepal.Width, simulate.p.value = T)
x$p.value
[1] 0.04797601

在你的情况下,如果你只想获得 p.values 的列表,你只需从应用函数中的对象中提取它:

# To get a list of p.values
lapply(vars, function(i) {
    res <- fisher.test(dataframe[[i]], dataframe$yvar)
    return(res$p.value)
})

# To get a full data frame
tbl <- lapply(vars, function(i) {
    res <- fisher.test(dataframe[[i]], dataframe$yvar)
    df <- data.frame(var = i,
                     p = res$p.value)
    return(df)
})

# Convert to data.frame in baseR
as.data.frame(t(sapply(tbl, rbind)))

# Convert to data.frame in tidyverse
dplyr::bind_rows(tbl)

如果您真的想保留默认输出,只显示更正后的 data 值,您可以手动编辑结果对象:

x <- fisher.test(iris$Petal.Length, iris$Sepal.Width, simulate.p.value = T)
x

    Fisher's Exact Test for Count Data with simulated p-value
    (based on 2000 replicates)

data:  iris$Petal.Length and iris$Sepal.Width
p-value = 0.04798
alternative hypothesis: two.sided

如您所见,数据值基于我们放入测试中的内容。不过,我们可以将其编辑为我们想要的任何内容,并且它将在默认打印中显示该输出:

x$data.name <- 'cat'
x

    Fisher's Exact Test for Count Data with simulated p-value
    (based on 2000 replicates)

data:  cat
p-value = 0.04798
alternative hypothesis: two.sided

在您的具体示例中,您的代码将如下所示:

lapply(vars, function(i) {
    res <- fisher.test(dataframe[[i]], dataframe$yvar)
    res$data.name <- paste0("dataframe$", i, " and dataframe$yvar")
    return(res)
})