0

所以我有这个数据并试图完成kruskal.test()一个包含数据框的列表

df_list <- list(
  `1.3.A` = 
    tibble::tribble(
      ~Person, ~Height, ~Weight,
      "Alex",    175L,     75L,
      "Gerard",    180L,     85L,
      "Clyde",    179L,     79L,
      "Alex",    175L,     75L,
      "Gerard",    180L,     85L,
      "Clyde",    179L,     79L

    ),
  `2.2.A` = 
    tibble::tribble(
      ~Person, ~Height, ~Weight,
      "Alex",    175L,     75L,
      "Gerard",    180L,     85L,
      "Clyde",    179L,     79L,
       "Alex",    175L,     75L,
      "Gerard",    180L,     85L,
      "Clyde",    179L,     79L
    ), 
  `1.1.B` = 
    tibble::tribble(
      ~Person, ~Height, ~Weight,
      "Alex",    175L,     75L,
      "Gerard",    180L,     85L,
      "Clyde",    179L,     79L,
      "Alex",    175L,     75L,
      "Gerard",    180L,     85L,
      "Clyde",    179L,     79L
    )
)

我试图kruskal.test在这 3 个数据帧上执行,但在试图找到解决方案数小时后失败了。我是 R 的新手。

失败的尝试是:

snake <- function(i){
  kruskal.test(df$Height ~ df$Person, data = i)
}
snail <- lapply(df_list, "[[", snake)


df_list %>% kruskal.test(df$Height ~ df$Person)

sapply(df_list, function(i) { kruskal.test(df$Height ~ df$Person, data = i)})


Map(function(x) kruskal.test(Height ~ Person), get(df_list))

Map(function(df_list, .f(kruskal.test(Height ~ Person)))

lapply(mget(df_list), function(x) kruskal.test(Height ~ Person))

bunny <- df_list %>%
  kruskal_test(df$Height ~ Person, data = .)

摘要:我正在尝试kruskal.test()处理一组包含数据框的列表。如何传递公式lapply()或在列表中的每个数据框中Map()运行?kruskal.test()

4

1 回答 1

2

您的代码引用了一个名为“df”的对象,该对象似乎不存在。此外,kruskal.test与 arguments 一起使用时kruskal.test(formula, data),无需在公式中引用数据框。提供kruskal.test“数据”参数将导致函数首先在提供的数据中搜索公式符号。换句话说,如果数据框“x”包含“Height”和“Person”列,那么以下内容将起作用:

kruskal.test(Height ~ Person, data = x)

在您的示例中,您不应引用df. 请注意,下面的代码创建了一个带有名为“i”的参数的临时函数,并且随后引用了“i”:

lapply(df_list, function(i) kruskal.test(Height ~ Person, data = i))

$`1.3.A`

    Kruskal-Wallis rank sum test

data:  Height by Person
Kruskal-Wallis chi-squared = 5, df = 2, p-value = 0.08208


$`2.2.A`

    Kruskal-Wallis rank sum test

data:  Height by Person
Kruskal-Wallis chi-squared = 5, df = 2, p-value = 0.08208


$`1.1.B`

    Kruskal-Wallis rank sum test

data:  Height by Person
Kruskal-Wallis chi-squared = 5, df = 2, p-value = 0.08208
于 2021-08-21T17:50:06.623 回答