Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to "unmelt" the dataframe into matrix

I have a dataframe

sources <- c("a", "b", "c", "a", "a", "b")
targets <- c("f", "v", "w", "a", "b", "c")
values <- c(12, 34, 56, 3, 76, 35)
df <- data.frame(sources, targets, values)

  sources targets values
1       a       f     12
2       b       v     34
3       c       w     56
4       a       a      3
5       a       b     76
6       b       c     35

How to reshape it to get a matrix with sources as row names, targets as colnames and corresponding values in intersecting cells? In this case, I should have a 3 by 6 matrix. something like this:

    f  v  w  a  b  c
a  12  0  0  3  76 0
b  0  34  0  0  0 35 
c  0  0   56 0  0  0

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You may try

library(tidyverse)

df <- data.frame(sources, targets, values)

df %>%
  pivot_wider(names_from = targets, values_from = values) %>%
  replace(is.na(.), 0) %>%
  column_to_rownames(var = "sources")


   f  v  w a  b  c
a 12  0  0 3 76  0
b  0 34  0 0  0 35
c  0  0 56 0  0  0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading