PersianK
PersianK

Reputation: 97

Obtain a matrix from a dataframe R

I'm working on clustering and I need to tranform my data in matrix. This is my df:

       el1 el2 value
    1   a   x     1
    2   a   y     2
    3   a   z     3
    2   b   x     2
    3   b   y     3
    3   b   z     3

I need to transform it in matrix, having el1 and el2 as rows and cols names and the corresponding value.

  x y z 
a 1 2 3
b 2 3 3

How I can do? Thanks!

Upvotes: 1

Views: 46

Answers (3)

user2974951
user2974951

Reputation: 10375

Using reshape2 and some magic (I created my own data)

df=read.table(text="
el1 el2 value
a   w     1
a   x     2
a   y     3
a   z     4
b   x     1
b   y     2
b   z     3
c   y     1
c   z     2
d   z     1",h=T)

then

library(reshape2)
df2=dcast(
  df,
  el1~el2,
  value.var="value"
)
rownames(df2)=df2$el1
df2=subset(df2,select=-c(el1))

   w  x  y z
a  1  2  3 4
b NA  1  2 3
c NA NA  1 2
d NA NA NA 1

if your original data only contains data for the upper or lower triangle of a matrix then you can copy the other with

df2[lower.tri(df2)]=t(df2)[lower.tri(df2)]

Upvotes: 2

Vincent Guillemot
Vincent Guillemot

Reputation: 3429

Here is a solution based on tidyr's pivot_wider function:

library(dplyr)
library(magrittr)
library(tidyr)

res <- df %>% 
  pivot_wider(
    id_cols = el1,
    names_from = el2,
    values_from = value) %>% 
  data.frame()

rownames(res) <- res$el1

(res %<>% select(-el1))

  x y z
a 1 2 3
b 2 3 3

It needs a little bit of work because tibbles do not like row names.

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 101343

A base R option using ´xtabs`

> xtabs(value ~ ., df)
   el2
el1 x y z
  a 1 2 3
  b 2 3 3

Upvotes: 2

Related Questions