在表中添加数据框的名称

时间:2019-02-27 09:33:23

标签: r purrr

我想在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)。有人可以解释一下我该怎么做吗?

3 个答案:

答案 0 :(得分:1)

我们可以先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

答案 1 :(得分:1)

您可以使用ls()和一个简单的正则表达式来捕获测试,即

v1 <- ls()[grepl('^t[0-9]+', ls())]
#[1] "t1" "t2" "t3"

然后您可以像往常一样(v1)将df$namess <- v1附加到数据框

答案 2 :(得分:1)

使用命名列表,您将在结果表中获取名称:

ll <- list(t1 = t1, t2 = t2, t3 = t3)
tab <-
  ll %>%
  map_df(tidy, .id = "id")