Home > Back-end >  R pipe operator %T>%
R pipe operator %T>%

Time:01-23

who will advise me on the %T>%,

the code is

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

however, it always bypass the fisher.test just conduct the chisq.test. my plan is the data will be output into fisher and chisq test respectively.

your advice is highly appreciated!

Charles

CodePudding user response:

You don't need Tee pipe for this.

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

Created on 2022-01-22 by the reprex package (v2.0.1)

CodePudding user response:

The problem is although the data is returned after your test, your test result is not printed. This can be overcomed by defining a Print functional that forces the print of each step. Then you can %T>% as many times as you want. One benefit of this is that you can also "switch off" those steps that you do not want to be printed to the console by just stripping off the Print wrapper.

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)()

Note that the () after Print(...) is compulsory.

Output

    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
  •  Tags:  
  • Related