使用lapply函数与emmeans列表。

5

我正在使用emmeans包,但不明白为什么它能够工作

library(emmeans)
mod <- lm(mpg ~ disp + hp, data = mtcars)
l1 <- emmeans(mod, list("disp","hp"))

for (x in l1) {print(data.frame(x))}

      disp   emmean        SE df lower.CL upper.CL
1 230.7219 20.09062 0.5527102 29 18.96021 21.22104
        hp   emmean        SE df lower.CL upper.CL
1 146.6875 20.09062 0.5527102 29 18.96021 21.22104

但这个不行吗?

lapply(l1, function(x) data.frame(x))

 Error in as.data.frame.default(x[[i]], optional = TRUE) : 
cannot coerce class"function"’ to a data.frame

使用普通列表,我可以得到预期的输出(列表中的数据框):

l2 <- list(a=matrix(c(1,2,3,4)), b=matrix(c(5,6,7,8)))
lapply(l2, function(x) data.frame(x))
$a
  x
1 1
2 2
3 1
4 3

$b
  x
1 4
2 5
3 4
4 6

看起来像是奇怪的行为。在 ?emmeans 中,当 specs 是一个列表时,你会得到一个 ?emm_list 对象,它有一个 as.data.frame 方法,因此你可以执行 as.data.frame(l1) 但它会产生警告。 - rawr
1
如果你使用 Map(data.frame, l1),它就能正常工作。看起来值得提交一个错误报告。 - Ritchie Sacramento
1
lapply(l1, \(x) data.frame(as.emmGrid(x))) 也是一个选项。 - Ritchie Sacramento
1个回答

2

它使用lapply将类从emmGrid修改为list

> lapply(l1, class)
$`emmeans of disp`
[1] "list"

$`emmeans of hp`
[1] "list"

相比之下,循环遍历序列并提取不是最佳选择。

> lapply(seq_along(l1), \(i) class(l1[[i]]))
[[1]]
[1] "emmGrid"
attr(,"package")
[1] "emmeans"

[[2]]
[1] "emmGrid"
attr(,"package")
[1] "emmeans"

因此,as.data.frame.list 将应用于 list 的所有元素(这些元素可能具有不同的结构、长度等)。一种选择是使用 mapas_tibble
library(tibble)
library(purrr)
> map(l1, as_tibble)
$`emmeans of disp`
# A tibble: 1 × 6
   disp emmean    SE    df lower.CL upper.CL
  <dbl>  <dbl> <dbl> <dbl>    <dbl>    <dbl>
1  231.   20.1 0.553    29     19.0     21.2

$`emmeans of hp`
# A tibble: 1 × 6
     hp emmean    SE    df lower.CL upper.CL
  <dbl>  <dbl> <dbl> <dbl>    <dbl>    <dbl>
1  147.   20.1 0.553    29     19.0     21.2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接