Jimmy Lee
Jimmy Lee

Reputation: 117

How to transform a table of dataset to a matrix in R

I have a dataset like this

df <- data.frame("col1" = c("a", "b", "a", "c", "d", "e", "f", "c"), "col2" = c("v2", "v2", "v2", "v3", "v4", "v1", "v2", "v4"), "index" = c(3,1,3,0,1,2,3,0))

And I hope to get a matrix like this:

  v1 v2 v2 v3 v4
a 0  3  3  0  0
b 0  1  0  0  0
c 0  0  0  0  0
d 0  0  0  0  1
e 2  0  0  0  0
f 0  3  0  0  0

Thank you very much for your answer!!

Upvotes: 0

Views: 46

Answers (2)

akrun
akrun

Reputation: 887118

We can do this easily in base R

xtabs(index ~ col1 + col2, unique(df))
#  col2
#col1 v1 v2 v3 v4
#   a  0  3  0  0
#   b  0  1  0  0
#   c  0  0  0  0
#   d  0  0  0  1
#   e  2  0  0  0
#   f  0  3  0  0

NOTE: No packages loaded

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388982

You do not have unique identifier in your groups and have values (V2) repeated. We can complete col1 and col2 values and fill index with 0. Create a unique identifier for each group (col1) and then spread the values.

library(tidyverse)

df %>%
  complete(col1, col2, fill = list(index = 0)) %>% 
  group_by(col1) %>%
  mutate(col2 = paste0("V", row_number())) %>%
  spread(col2, index, fill = 0)

#  col1     V1    V2    V3    V4    V5
#  <fct> <dbl> <dbl> <dbl> <dbl> <dbl>
#1 a         0     3     3     0     0
#2 b         0     1     0     0     0
#3 c         0     0     0     0     0
#4 d         0     0     0     1     0
#5 e         2     0     0     0     0
#6 f         0     3     0     0     0

Upvotes: 2

Related Questions