rnorouzian
rnorouzian

Reputation: 7517

Paste outputs of two functions to each other in a loop in R

I'm trying to paste the output of cat to right after CrossTable output. That is, at each iteration, first CrossTable output comes and right after it, cat is generated.

However, I can't achieve that with my current code, is there a way to achieve that in R?

library(gmodels)
library(vcd)

z <- data.frame(A = rep(c('Yes','No'), 5), B = sample(c('Yes','No'), 10, replace = T), group = rep(c('Treat', 'Cont'), each = 5))

lapply(names(z)[-3], function(x){ CrossTable(z[[x]], z$group, expected = F, format="SPSS", chisq= T, prop.t = F, dnn = c(x, "Group"));
 cat(paste('cramer =', round(assocstats(table(z[[x]], z$group))[[5]], 3))) #%@ paste to `CrossTable` output
})

Upvotes: 1

Views: 137

Answers (1)

akrun
akrun

Reputation: 886938

We can do this with a for loop after capturing the output from CrossTable and using append = TRUE in both capture.output and in the cat by writing the contents to the same file

for(i in 1:2) {
      capture.output(CrossTable(z[[i]], z$group, expected = FALSE,
          format="SPSS", chisq= T, prop.t = F, dnn = c(names(z)[i], "Group")), 
              file = "tempnew.txt", append = TRUE)
     cat(paste('cramer = ', round(assocstats(table(z[[i]], z$group))[[5]], 3)),
           file =  'tempnew.txt', append = TRUE, '\n')
     cat('\n\n\n********************************\n\n\n', 
                  file = 'tempnew.txt', append = TRUE, '\n')
    }

-contents of 'tempnew.txt'

enter image description here

Upvotes: 1

Related Questions