Home > database >  Obtain a matrix from a dataframe R
Obtain a matrix from a dataframe R

Time:03-04

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!

CodePudding user response:

Using reshape2 and some magic

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

  x y z
a 1 2 3
b 2 3 3

CodePudding user response:

A base R option using ´xtabs`

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

CodePudding user response:

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.

  • Related