Kevin Roth Kevin Roth - 1 year ago 120
R Question

Write results paired t.test in csv

I am performing a paired t test on data of multiple groups and would like to "export" this into a .csv file

Here's the data:

table <- read.table(text=' group M1 M2
Group 1 0.5592884 0.5592884
Group 1 0.3481799 0.3481799
Group 1 0.2113786 0.2113786
Group 1 0.2817871 0.2817871
Group 2 0.2543952 0.2543952
Group 2 0.2016288 0.2016288
Group 2 0.2098503 0.2098503
Group 2 0.1060097 0.1060097
Group 3 0.2405704 0.2405704
Group 3 0.3200119 0.3200119
Group 3 0.2453895 0.2453895
Group 3 1.3107510 1.3107510
Group 4 0.8600338 0.8600338
Group 4 0.5381423 0.5381423
Group 4 0.7348685 0.7348685
Group 4 0.2969512 0.2969512', header=TRUE)


as I don't want to compare M1 to M2 but the groups to each other, I perform the paired t.test as follows:

sig<-lapply(table[2:3], function(x)
pairwise.t.test(x, table$group,
p.adjust.method = "BH"))


However, as the result is a list, I cannot write is in a .csv file with this:

sink('test.csv')
cat('paired t results')
write.csv(sig)
sink()


I tried to work around by using
capture.output
, but this looses the separation

sig_output<-capture.output(print(sig))


is there a way to directly write
sig
into a csv file or a workouround?

Thank you!

Answer Source

Just use print after sink:

print(sig)

But note that the result is not a CSV file, contrary to what your code says. If you just want to save the p-value table, you could do something like the following:

save_p_values = function (test_data, filename) {
    write.csv(test_data$p.value, filename)
}

Map(save_p_values, sig, paste0(names(sig), '.csv'))

To get both tables in the same file, you need to add a column that distinguishes them; using ‹dplyr›:

sig_combined = sig %>%
    # Extract p-value tables
    map(`[[`, 'p.value') %>%
    # Convert matrix to data.frame so we can work with dplyr
    map(as.data.frame) %>%
    # Preserve rownames by saving them into column:
    map(tibble::rownames_to_column, 'Contrast') %>%
    # Add name of column that t-test was performed on
    map2(names(.), ~ mutate(.x, Col = .y)) %>%
    # Merge into one table
    bind_rows()

write.csv(sig_combined, 'results.csv')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download