BloopFloopy
BloopFloopy

Reputation: 139

How to get a tidy excel output of P values from R

How to get a clean excel dataset of P-values which are exported from R using

res <- rcorr(as.matrix(df), type = c("pearson"))

I have used the code above to find the P-values across all variables in my data. However, I was interested in exporting these findings into an excel sheet. I have done this by using the following code:

write.table(P_val, file="df.csv", sep = ",")

The output from this is an excel sheet, however the data is not "tidy" in the sense that all data are in rows, cramped into the same cells, and it is not possible to read the data as there is no sense in how the data are related each variable in this set-up.

What I would like, are tables that indicate the P-value for each variable across all variables.

So what I have done so far is (here I am using simple dataset from R to show what i mean):

 df <- USArrests

 res <- rcorr(as.matrix(df), type = c("pearson"))

 P_val <- res$P

 write.table(P_val, file="P_val.csv", sep = ",")

I don't really know how to move forward from here, so I hope that someone can help me :-)

Upvotes: 0

Views: 915

Answers (1)

neilfws
neilfws

Reputation: 33772

I'd use broom::tidy, and readr::write_csv to write it out.

library(Hmisc) # for rcorr
library(broom)
library(magrittr) # for pipes %>%
library(readr)

as.matrix(USArrests) %>% 
  rcorr(type = "pearson") %>%
  tidy() %>%
  write_csv("P_val.csv")

Result (before write_csv):

# A tibble: 6 x 5
  column1  column2  estimate     n  p.value
  <chr>    <chr>       <dbl> <int>    <dbl>
1 Murder   Assault    0.802     50 2.60e-12
2 Murder   UrbanPop   0.0696    50 6.31e- 1
3 Assault  UrbanPop   0.259     50 6.95e- 2
4 Murder   Rape       0.564     50 2.03e- 5
5 Assault  Rape       0.665     50 1.36e- 7
6 UrbanPop Rape       0.411     50 3.00e- 3

Upvotes: 3

Related Questions