1

我正在对多个组的数据进行配对 t 检验,并希望将其“导出”到 .csv 文件中

这是数据:

 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)

因为我不想将 M1 与 M2 进行比较,而是将组相互比较,所以我执行配对 t.test 如下:

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

但是,由于结果是一个列表,我不能在 .csv 文件中写入:

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

我试图通过使用来解决capture.output,但这会失去分离

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

有没有办法直接写入sigcsv 文件或解决方法?

谢谢!

4

1 回答 1

2

只需print在之后使用sink

print(sig)

但请注意,结果不是CSV 文件,这与您的代码所说的相反。如果您只想保存 p 值表,可以执行以下操作:

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

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

要在同一个文件中获取两个表,您需要添加一个区分它们的列;使用‹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')
于 2017-11-24T13:44:12.417 回答