% map_dfr(tidy, .id = "Test") ta-6ren">
gpt4 book ai didi

r - 在表中添加数据框的名称

转载 作者:行者123 更新时间:2023-12-01 08:02:34 24 4
gpt4 key购买 nike

我想在 t 检验表中添加数据框的名称。这是我的示例代码:

t1 <- t.test(rnorm(100), rnorm(100)
t2 <- t.test(rnorm(100), rnorm(100, 1))
t3 <- t.test(rnorm(100), rnorm(100, 2))

现在我用 broom 和 purrr 包把它们变成一个数据框(然后可以打印成表格):

library(broom)
library(purrr)

tab <- map_df(list(t1, t2, t3), tidy)

现在我得到这张表:

 estimate    estimate1   estimate2  statistic      p.value parameter   conf.low  conf.high
1 0.07889713 -0.008136139 -0.08703327 0.535986 5.925840e-01 193.4152 -0.2114261 0.3692204
2 -0.84980010 0.132836627 0.98263673 -6.169076 3.913068e-09 194.2561 -1.1214809 -0.5781193
3 -1.95876967 -0.039048940 1.91972073 -13.270232 3.618929e-29 197.9963 -2.2498519 -1.6676875
method alternative
1 Welch Two Sample t-test two.sided
2 Welch Two Sample t-test two.sided
3 Welch Two Sample t-test two.sided

最后我想在第一列中添加数据帧的名称 (t1,t2,t3)。谁能解释一下我该怎么做?

最佳答案

我们可以先set_names,然后使用.id参数来添加列。

set.seed(123)

t1 <- t.test(rnorm(100), rnorm(100))
t2 <- t.test(rnorm(100), rnorm(100, 1))
t3 <- t.test(rnorm(100), rnorm(100, 2))

library(broom)
library(purrr)

tab <- list(t1, t2, t3) %>%
set_names(paste0("t", 1:3)) %>%
map_dfr(tidy, .id = "Test")
tab
# # A tibble: 3 x 11
# Test estimate estimate1 estimate2 statistic p.value parameter conf.low conf.high method alternative
# <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <chr> <chr>
# 1 t1 0.198 0.0904 -0.108 1.49 1.38e- 1 197. -0.0643 0.460 Welch Two Samp~ two.sided
# 2 t2 -0.843 0.120 0.964 -5.99 9.79e- 9 196. -1.12 -0.566 Welch Two Samp~ two.sided
# 3 t3 -1.85 0.106 1.96 -13.6 4.31e-30 197. -2.12 -1.58 Welch Two Samp~ two.sided

关于r - 在表中添加数据框的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54902155/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com