heyflypig - 1 year ago 47

R Question

How to transform a matrix like

`A 1 2 3`

B 3 6 9

c 5 6 9

D 1 2 4

into form like:

`1 2 3 4 5 6 7 8 9`

1 0 2 1 1 0 0 0 0 0

2 0 0 1 1 0 0 0 0 0

3 0 0 0 0 0 1 0 0 1

4 0 0 0 0 0 0 0 0 0

5 0 0 0 0 0 1 0 0 1

6 0 0 0 0 0 0 0 0 2

7 0 0 0 0 0 0 0 0 0

8 0 0 0 0 0 0 0 0 0

9 0 0 0 0 0 0 0 0 0

I have some implement for it ,but it use the for loop

I wonder if there has some inner function in R (for example "apply")

add:

Sorry for the confusion.The first matrix just mean items sets, every set of items come out pairs ,for example the first set is "1 2 3" , and will become (1,2),(1,3),(2,3), correspond the second matrix.

and another question :

If the matrix is very large (10000000*10000000)and is sparse

should I use sparse matrix or big.matrix?

Thanks!

Answer Source

Removing the row names from M gives this:

```
m <- matrix(c(1,3,5,1,2,6,6,2,3,9,9,4), nrow=4)
> m
## [,1] [,2] [,3]
## [1,] 1 2 3
## [2,] 3 6 9
## [3,] 5 6 9
## [4,] 1 2 4
# The indicies that you want to increment in x, but some are repeated
# combn() is used to compute the combinations of columns
indices <- matrix(t(m[,combn(1:3,2)]),,2,byrow=TRUE)
# Count repeated rows
ones <- rep(1,nrow(indices))
cnt <- aggregate(ones, by=as.data.frame(indices), FUN=sum)
# Set each value to the appropriate count
x <- matrix(0, 9, 9)
x[as.matrix(cnt[,1:2])] <- cnt[,3]
x
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
## [1,] 0 2 1 1 0 0 0 0 0
## [2,] 0 0 1 1 0 0 0 0 0
## [3,] 0 0 0 0 0 1 0 0 1
## [4,] 0 0 0 0 0 0 0 0 0
## [5,] 0 0 0 0 0 1 0 0 1
## [6,] 0 0 0 0 0 0 0 0 2
## [7,] 0 0 0 0 0 0 0 0 0
## [8,] 0 0 0 0 0 0 0 0 0
## [9,] 0 0 0 0 0 0 0 0 0
```