Matrix restructuring

Hi there,

I am struggling with restructuring of the following matrix:

vec1 <- c("t1","t2","t1","t2","t1","t2")
vec2 <- c(15,61,44,15,35,11)
vec3 <- c("a", "a" , "b", "b", "c", "c")

  vec1 vec2 vec3
   t1   15    a
   t2   61    a
   t1   44    b
   t2   15    b
   t1   35    c
   t2   11    c

I would like to create a new matrix, looks like the following:

      a    b     c 
t1 15  44  35
t2 61  15  11

In words:

  1. the entries in vec3 to be 3 distinct columns or column headers (but only the unique letters a, b & c).
  2. vec1 to be a column (again only unique values: t1 & t2)
  3. and vec 3 to become the entries

I would very much appreciate your help, as I am quite new to restructuring data.

Thx,
Felix


(mymat <- as.matrix(data.frame(
           vec1= c("t1","t2","t1","t2","t1","t2"),
           vec2=c(15,61,44,15,35,11),
           vec3=c("a", "a" , "b", "b", "c", "c"))))

(mydat <- as.data.frame(mymat))

library(tidyverse)

(mydat_w <- pivot_wider(mydat,
                       names_from = "vec3",
                       values_from = "vec2") %>% 
    mutate(across(-vec1,as.numeric)))

(mymat_w <- select(mydat_w,-vec1) %>% as.matrix)
rownames(mymat_w) <- pull(mydat_w,vec1)

mymat_w
1 Like

Hi @nirgrahamuk,

thank you for the quick reply earlier today - it does the job!
However, I have one follow-up question: Say, there is one more vector/column in the initial matrix that should just be included. If I got the pivot_wider function right, it omits the "unused" columns. Which argument would pull the remaining column?

Thx,
Felix

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.