我怎样才能得到一个整洁的" purrr :: map2的结果?

时间:2017-09-27 06:59:50

标签: r tidyr purrr broom

给定一个数据框,其中包含两个不同变量的重复测量值(即A1, A2, B1, B2

library(purrr)
library(tidyr)
library(broom)

set.seed(123)

my_df = data.frame(matrix(rnorm(80), nrow=10))
colnames(my_df) <- c("A1_BEFORE", "A1_AFTER", "A2_BEFORE", "A2_AFTER",
                     "B1_BEFORE", "B1_AFTER", "B2_BEFORE", "B2_AFTER")

如何使用函数式编程原理迭代相同变量的对(BEFORE,AFTER),并获得&#34; tidy&#34;结果?这是我的尝试:

bef <- select(my_df, contains("BEFORE"))
aft <- select(my_df, contains("AFTER"))
result <- map2(bef, aft, t.test, paired = T)

以上结果是多个嵌套列表。我怎么能得到一个整洁的&#34;结果?

result <- tidy(map2(bef, aft, t.test, paired = T))
  

结果&lt; - tidy(map2(bef,aft,t.test,paired = T))
  tidy.list中的错误(map2(bef,aft,t.test,paired = T)):         没有为此列表识别整理方法       另外:警告信息:       在sort(names(x))== c(&#34; d&#34;,&#34; u&#34;,&#34; v&#34;)中:         较长的物体长度不是较短物体长度的倍数

2 个答案:

答案 0 :(得分:2)

我们可以使用map_df,因为它是list

map2(bef, aft, t.test, paired = TRUE) %>%
            map_df(tidy)
#   estimate  statistic    p.value parameter   conf.low conf.high        method
#1 -0.1339963 -0.4613684 0.65548187         9 -0.7909999 0.5230073 Paired t-test
#2 -0.7466034 -1.8820475 0.09250351         9 -1.6439954 0.1507885 Paired t-test
#3 -0.2304015 -0.5740849 0.57997286         9 -1.1382891 0.6774860 Paired t-test
#4  0.4860015  1.3468795 0.21095133         9 -0.3302644 1.3022674 Paired t-test
#   alternative
#1   two.sided
#2   two.sided
#3   two.sided
#4   two.sided

或更紧凑

map2_df(bef, aft, ~tidy(t.test(.x, .y, paired = TRUE)))

答案 1 :(得分:2)

这是一种替代方法,在进行t检验之前整理数据。显然得到相同的结果,但这种方法标记了在最终输出中测试的变量。

仅更改为数据添加了一个id变量来索引重复的度量

除了broom

之外,

还需要tidyrdplyr

library(tidyr, dplyr, broom)

使用tidyr进行重组

my_tidy_df <- my_df %>% 
  mutate(id = row_number()) %>% # needs an id to group repeated measure
  gather(var, value, -id) %>% 
  extract(var, c("var", "timepoint"), "([[:alnum:]]+)_([[:alnum:]]+)") %>% 
  spread(timepoint, value) 

给出了这个结构

   id var       AFTER     BEFORE
1   1  A1 -1.14854253 -0.9032172
2   1  A2  2.36114529 -0.6500869
3   1  B1  0.26204456 -0.5477532
4   1  B2 -1.34416890 -0.4696884
5   2  A1  0.53400345  1.2722203
然后,您可以对每个变量运行t检验,如下所示:

my_tidy_df %>% 
  group_by(var) %>% 
  do(broom::tidy(t.test(.$BEFORE, .$AFTER, data=., paired=T)))

结果:

# Groups:   var [4]
    var    estimate  statistic   p.value parameter   conf.low conf.high        method alternative
  <chr>       <dbl>      <dbl>     <dbl>     <dbl>      <dbl>     <dbl>        <fctr>      <fctr>
1    A1  0.16014628  0.3470400 0.7365381         9 -0.8837567 1.2040493 Paired t-test   two.sided
2    A2 -0.99798993 -1.6271640 0.1381451         9 -2.3854407 0.3894609 Paired t-test   two.sided
3    B1  0.04916586  0.1289803 0.9002097         9 -0.8131436 0.9114753 Paired t-test   two.sided
4    B2 -0.06919212 -0.1833619 0.8585784         9 -0.9228233 0.7844391 Paired t-test   two.sided