Home > Blockchain >  Sorting vectors into matrices(9 x 3)
Sorting vectors into matrices(9 x 3)

Time:01-28

The aim is to create a array/matrix that sorts 3 rows of numbers (vectors) counting the numbers into the array.

vectors (x, y, z)

x <- 1 4 5 6
y <- 2 3 3 4 4 5 5 6 6 7 7 7 9
z <- 2 2 2 3 3 3 3 4 4 4 4 4 5 5 5 5 5 6 7 8 9 9

Matrices/array (ideal output)

      [,1] [,2] [,3]
 [1,]    1    0    0
 [2,]    0    1    3
 [3,]    0    2    4
 [4,]    1    2    5
 [5,]    1    2    5
 [6,]    1    2    1
 [7,]    0    3    1
 [8,]    0    0    1
 [9,]    0    1    2

I've tried but can only input numbers from vectors directly into the array.

I currently have a 9x3 matrix with all '0'. :(

task_six <- matrix(0, nrow = 9, ncol = 3)
task_six

      [,1] [,2] [,3]
 [1,]    0    0    0
 [2,]    0    0    0
 [3,]    0    0    0
 [4,]    0    0    0
 [5,]    0    0    0
 [6,]    0    0    0
 [7,]    0    0    0
 [8,]    0    0    0
 [9,]    0    0    0

CodePudding user response:

We can use tabulate to calculate the totals for each vector, and sapply to apply the calculation to all three vectors at once.

x <- c(1, 4, 5, 6)
y <- c(2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 7, 9)
z <- c(2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 7, 8, 9, 9)

max_value <- max(x, y, z)

result <- sapply(list(x, y, z), function(i) tabulate(i, max_value))

      [,1] [,2] [,3]
 [1,]    1    0    0
 [2,]    0    1    3
 [3,]    0    2    4
 [4,]    1    2    5
 [5,]    1    2    5
 [6,]    1    2    1
 [7,]    0    3    1
 [8,]    0    0    1
 [9,]    0    1    2

CodePudding user response:

We can try this

> lst <- list(x, y, z)

> table(stack(setNames(lst, seq_along(lst))))
      ind
values 1 2 3
     1 1 0 0
     2 0 1 3
     3 0 2 4
     4 1 2 5
     5 1 2 5
     6 1 2 1
     7 0 3 1
     8 0 0 1
     9 0 1 2

CodePudding user response:

Another possible solution, based on table and purrr::walk2. First, I create the m matrix only with zeros. Then I use table to fill m with the counts, iterating with walk2.

library(tidyverse)

x <- c(1,4,5,6)
y <- c(2,3,3,4,4,5,5,6,6,7,7,7,9)
z <- c(2,2,2,3,3,3,3,4,4,4,4,4,5,5,5,5,5,6,7,8,9,9)


m <- matrix(0, max(x,y,z), 3)

walk2(list(x,y,z), 1:3, ~ 
  assign("m", replace(m, cbind(as.integer(names(table(.x))), .y),
         table(.x)), envir = .GlobalEnv))

m

#>       [,1] [,2] [,3]
#>  [1,]    1    0    0
#>  [2,]    0    1    3
#>  [3,]    0    2    4
#>  [4,]    1    2    5
#>  [5,]    1    2    5
#>  [6,]    1    2    1
#>  [7,]    0    3    1
#>  [8,]    0    0    1
#>  [9,]    0    1    2
  •  Tags:  
  • Related