Home > Mobile >  R: creating a matrix using two id columns and the value column [duplicate]
R: creating a matrix using two id columns and the value column [duplicate]

Time:10-07

Purpose

I am trying to create a matrix using two id columns (period1, period2) and the value column (p) for each combination of ids. They are results of t-tests. I want to make a square matrix that shows p-value for each combination of ids, similar to correlation matrix.

Sample Data

  t <-
  structure(list(period1 = c("(1) Start (178)", "(1) Start (178)", 
    "(1) Start (178)", "(1) Start (178)", "(2) Mature (217)", "(2) Mature (217)", 
    "(2) Mature (217)", "(3) COVID hit (117)", "(3) COVID hit (117)", 
    "(4) After COVID (79)"), period2 = c("(2) Mature (178)", "(3) COVID hit (178)", 
    "(4) After COVID (178)", "(5) Closing (178)", "(3) COVID hit (217)", 
    "(4) After COVID (217)", "(5) Closing (217)", "(4) After COVID (117)", 
    "(5) Closing (117)", "(5) Closing (79)"), p = c("0.0000 (****)", 
    "0.0000 (****)", "0.0000 (****)", "0.0055 (**)", "0.0003 (***)", 
    "0.0727 (ns)", "0.0000 (****)", "0.2050 (ns)", "0.0000 (****)", 
    "0.0000 (****)")), row.names = c(NA, -10L), class = "data.frame")

CodePudding user response:

May be we need to reshape to 'wide' format

library(tidyr)
library(tibble)
library(dplyr)
t %>% 
   pivot_wider(names_from = period2, values_from = p) %>% 
   column_to_rownames('period1')
  • Related