将两个列表转换为 R 中的数据框

Convert two lists to dataframe in R

我对两个数据框进行了 t 检验,并将结果存储在两个单独的变量中。他们原来是名单。现在,我想制作一个包含 t 分数和 p 值的数据框,但我不确定该怎么做。我猜列表是 s3 class。代码.

AML_ttest <- apply(aml_df,1,t.test)
nrml_ttest <- apply(nrml_df,1,t.test)

运行 AML_ttest[[9]] 给出以下结果。

One Sample t-test

data:  newX[, i]
t = 25.994, df = 25, p-value < 2.2e-16
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
 6.612063 7.749997
sample estimates:
mean of x 
  7.18103 

如何从每个列表元素中获取 t 值和 p 值?并制作一个新的数据框?

谢谢。

---更新---

我尝试了以下代码。

# AML
AML_ttest <- apply(aml_df,1,t.test)
AML_ttest = do.call(rbind,AML_ttest)
res_AML_ttest <- AML_ttest[,c("statistic","p.value")]

# Normal
nrml_ttest <- apply(nrml_df,1,t.test)
nrml_ttest = do.call(rbind,nrml_ttest)
res_nrml_ttest <- nrml_ttest[,c("statistic","p.value")]

# Make df
df_ttest <- data.frame(res_AML_ttest, res_nrml_ttest)
df_ttest

# Output
     statistic   p.value    statistic.1 p.value.1
1    56.71269 6.171562e-28    144.5161 1.569932e-52
2    75.79649 4.559861e-31    74.87025 5.317292e-42
3    17.68306 1.207297e-15    15.15478 1.891711e-17
4    108.4904 5.984139e-35    168.8557 4.993433e-55
5    152.8165 1.156183e-38    192.4672 3.959361e-57
6    63.21714 4.163004e-29    90.42468 5.112986e-45

这个方法好吗?我可以走了吗?

在你的例子中有更多的数据通常会有帮助,但在这种情况下我们可以获得 p 值等等。尝试 AML_ttest[[9]]$p.value。要查看所有选项,请尝试 str(AML_ttest[[9]])str(summary(AML_ttest[[9]]))

软件包 broom 非常适合这个。尝试 broom::t.test(MyData)。如果您使用 tidyverse 语法按某个变量对数据进行分组,您可以这样做,例如 MyData %>% group_by(ColumnA) %>% do(tidy(t.test(.$ColumnB, .$ColumnC, paired = TRUE)))。 (注意“.”)

我将使用此示例数据进行测试:

TT1 <- apply(mtcars[1:3], 2, t.test)

我们可以查看其中之一的 str 结构以查看要查找的名称。

str(TT1[[1]])
# List of 10
#  $ statistic  : Named num 18.9
#   ..- attr(*, "names")= chr "t"
#  $ parameter  : Named num 31
#   ..- attr(*, "names")= chr "df"
#  $ p.value    : num 1.53e-18
#  $ conf.int   : num [1:2] 17.9 22.3
#   ..- attr(*, "conf.level")= num 0.95
#  $ estimate   : Named num 20.1
#   ..- attr(*, "names")= chr "mean of x"
#  $ null.value : Named num 0
#   ..- attr(*, "names")= chr "mean"
#  $ stderr     : num 1.07
#  $ alternative: chr "two.sided"
#  $ method     : chr "One Sample t-test"
#  $ data.name  : chr "newX[, i]"
#  - attr(*, "class")= chr "htest"

这表明我们可以为此使用 "statistic""p.value"。直接方法:

TT1[[1]][ c("statistic", "p.value") ]
# $statistic
#        t 
# 18.85693 
# $p.value
# [1] 1.526151e-18

我们可以通过以下方式将它们收集起来:

out <- do.call(rbind.data.frame, lapply(TT1, `[`, c("statistic", "p.value")))
out
#      statistic      p.value
# mpg   18.85693 1.526151e-18
# cyl   19.59872 5.048147e-19
# disp  10.53069 9.189065e-12

其中 mpg 等是行名。如果需要,可以将它们带入框架本身,

out$name <- rownames(out)
rownames(out) <- NULL # aesthetics only, not required
out
#   statistic      p.value name
# 1  18.85693 1.526151e-18  mpg
# 2  19.59872 5.048147e-19  cyl
# 3  10.53069 9.189065e-12 disp

(由于您使用 apply(MARGIN=1) 制作了 t 检验列表,但如果原始数据没有好的行名称,它的命名可能没有意义。)