Search code examples
rmatrixprime-factoringtabulate

Creating a matrix for the following vector in R


A vector contains the following numerical data after prime factorization of a certain number x:

c  <- c(2,2,2,3) 

This is the prime factorization of 24

The first column of the matrix should contain the prime factors 2 and 3 The second column should contain the power of the prime factors.

e.g.

| 2  3 |

| 3  1 |

How would I go about creating this matrix.


Solution

  • With tabulate:

    f <- as.integer(gmp::factorize(24))
    cnts <- tabulate(f)[-1]
    matrix(c(unique(f), cnts[cnts > 0L]), ncol = 2)
    #>      [,1] [,2]
    #> [1,]    2    3
    #> [2,]    3    1
    

    Or with table:

    f <- table(as.integer(gmp::factorize(24)))
    matrix(c(as.integer(names(f)), f), ncol = 2)
    #>      [,1] [,2]
    #> [1,]    2    3
    #> [2,]    3    1