Home > Software engineering >  Creating a matrix for the following vector in R
Creating a matrix for the following vector in R

Time:10-20

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.

CodePudding user response:

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

CodePudding user response:

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
  • Related