1

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.

ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
Mike
  • 13
  • 2

2 Answers2

0

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
jblood94
  • 10,340
  • 1
  • 10
  • 15
0

Here is a base R option by defining a function to factorize an integer, e.g.,

f <- function(n) {
  k <- 2
  v <- c()
  while (k <= n) {
    if (n %% k == 0) {
      v <- c(v, k)
      n <- n / k
    } else {
      k <- k + 1
    }
  }
  as.data.frame(table(v))
}

and you will see, for example

> f(24)
  v Freq
1 2    3
2 3    1

> f(46788)
    v Freq
1   2    2
2   3    1
3   7    1
4 557    1
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81