R管道运算符%T>%

3

谁可以就%T>%向我提供咨询,

代码如下:

c(1031, 8, 0, 968, 66, 12) %>% 
  matrix(ncol = 3) %>% 
  'colnames<-'(c("Improved", "Hospitalized", "Death")) %>% 
  'rownames<-'(c("Treated", "Placebo")) %>% 
  as.table %T>% fisher.test %>% chisq.test

然而,它总是绕过 fisher.test 只进行 chisq.test。我的计划是将数据分别输出到 fisher 和 chisq 测试中。

非常感谢您的建议!

查尔斯


1
为了将数据进行Tee-pipe,函数需要以不可见的方式返回数据,以便您可以进一步进行管道处理。tidyverse内部的函数是按照这种设计来实现的,但其他函数则不然。 - Claudiu Papasteri
2个回答

3

这不需要使用Tee管。

library(magrittr)

c(1031, 8, 0, 968, 66, 12) %>% 
  matrix(ncol = 3) %>% 
  'colnames<-'(c("Improved", "Hospitalized", "Death")) %>% 
  'rownames<-'(c("Treated", "Placebo")) %>% 
  as.table %>% 
  {fisher.test(.) %>% print() 
   chisq.test(.) %>% print()}
#> 
#>  Fisher's Exact Test for Count Data
#> 
#> data:  .
#> p-value < 2.2e-16
#> alternative hypothesis: two.sided
#> 
#> 
#>  Pearson's Chi-squared test
#> 
#> data:  .
#> X-squared = 2012.4, df = 2, p-value < 2.2e-16

此内容由 reprex包 (v2.0.1) 于2022-01-22创建


这是一种非常聪明的方式。然而,作为初学者,我只想练习 %T>% 的用法。 - charles

1

问题在于,虽然测试返回了数据,但测试结果没有被打印出来。这可以通过定义一个 Print 函数来解决,该函数强制打印每个步骤。然后您可以随意使用 %T>%。其中一个好处是,您也可以通过仅剥离 Print 包装器来“关闭”那些您不想打印到控制台的步骤。

library(magrittr)

Print <- function(f) function(x) print(f(x))

c(1031, 8, 0, 968, 66, 12) %>% 
  matrix(ncol = 3) %>% 
  'colnames<-'(c("Improved", "Hospitalized", "Death")) %>% 
  'rownames<-'(c("Treated", "Placebo")) %>% 
  as.table %T>% Print(fisher.test)() %T>% Print(chisq.test)() %T>% Print(t.test)()

请注意,在Print(...)后面必须加上()
输出
    Fisher's Exact Test for Count Data

data:  x
p-value < 2.2e-16
alternative hypothesis: two.sided


    Pearson's Chi-squared test

data:  x
X-squared = 2012.4, df = 2, p-value < 2.2e-16


    One Sample t-test

data:  x
t = 1.6823, df = 5, p-value = 0.1533
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
 -183.4795  878.4795
sample estimates:
mean of x 
    347.5 

        Improved Hospitalized Death
Treated     1031            0    66
Placebo        8          968    12

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接