Search code examples
radjacency-matrix

Building an adjacency matrix in R


Helo Everyone, here is my problem.

using

> visite_cliente <- aggregate(info.uso.2$N,list(CodCliente = info.uso.2$CodCliente, museo = info.uso.2$museo),sum)

I created the following matrix :

> head(visite_cliente)

   CodCliente           museo      x
1       1247 ABBAZIA DI FRUTTUARIA 1
2       3260 ABBAZIA DI FRUTTUARIA 1
3       4104 ABBAZIA DI FRUTTUARIA 1
4       4145 ABBAZIA DI FRUTTUARIA 1
5       5368 ABBAZIA DI FRUTTUARIA 1
6       5530 ABBAZIA DI FRUTTUARIA 1

CodCliente is my customer's ID, while "museo" is the museum visited by the customer (I have 139 museums in the dataframe), and X value represent the times that customer visited the museum in a year. In "visite_cliente" you can find the same ID more than one time if the customer visited more than a museum.

I should create an adjacency matrix in which I have as columns the museums (so 139 columns), the IDs in the rows, and insert the times the customer visited each museum in the matrix.

Thank you


Solution

  • This is a classic long-wide reshape problem

    just do

    library(data.table)
    
    dcast(data = visite_cliente, CodCliente ~ museo, value.var = "x")