0

I have table A with 2 columns of IDs. Each row represents a transaction between a buyer (buyerId) and a seller (sellerId).

I have created a blank matrix B with the rows corresponding to the buyerId and columns to the seller Id. I'd like to fill this matrix B with binary values, 1 representing a transaction between a buyer and a seller.

eg. row 200 in table A is 12345, 99887 (buyerId, sellerId)

For matrix B, the entry with the row named (not indexed!) 12345 and column named 99887 will have a 1.

How can I do this?

Qonl
  • 79
  • 1
  • 10
  • Possible duplicate of [Reshape three column data frame to matrix ("long" to "wide" format)](https://stackoverflow.com/questions/9617348/reshape-three-column-data-frame-to-matrix-long-to-wide-format) – emilliman5 Sep 30 '17 at 18:55
  • 1
    `with(yourdata, table(buyerid, sellerid))` might be enough. If not, can you add a *small* example of your data, and expected outcome please. – user20650 Sep 30 '17 at 19:10

1 Answers1

1

You can cast your matrix (converted to a data frame first)

mat <- matrix(c(sample(1:10, 5), sample(11:20, 5)), ncol=2)
mat <- as.data.frame(mat)
mat$value <- 1 

dcast(data = mat, V1 ~ V2, value.var = "value", sum)
# V1 15 16 17 18 20
# 1  2  0  0  0  0  1
# 2  6  1  0  0  0  0
# 3  8  0  0  1  0  0
# 4  9  0  1  0  0  0
# 5 10  0  0  0  1  0
emilliman5
  • 5,816
  • 3
  • 27
  • 37