'How to find mode of a multidimensional array in R
I have a multidimensional array
,,1
[,1] [,2]
[1,] "0" "a"
[2,] "1" "a"
[3,] "1" "b"
[2,] "1" "c"
[3,] "1" "c"
,,2
[,1] [,2]
[1,] "0" "a"
[2,] "1" "a"
[3,] "1" "a"
[2,] "0" "b"
[3,] "0" "c"
i just want to find the mode, if the first column is "1" for every group data. For this multidimensional array, i want output maybe like this
,,1
c
,,2
a
or
[1] c
[2] a
Solution 1:[1]
Suppose your array looks like this:
set.seed(1)
vec <- sample(c(0:3, letters[1:3]), 5 * 2 * 3, replace = TRUE)
dim(vec) <- c(5, 2, 3)
vec
#> , , 1
#>
#> [,1] [,2]
#> [1,] "0" "a"
#> [2,] "3" "c"
#> [3,] "c" "2"
#> [4,] "0" "b"
#> [5,] "1" "1"
#>
#> , , 2
#>
#> [,1] [,2]
#> [1,] "2" "1"
#> [2,] "2" "b"
#> [3,] "0" "b"
#> [4,] "a" "1"
#> [5,] "a" "c"
#>
#> , , 3
#>
#> [,1] [,2]
#> [1,] "0" "0"
#> [2,] "c" "b"
#> [3,] "a" "a"
#> [4,] "a" "a"
#> [5,] "0" "1"
Then you can find the most common entry in each slice of the array by doing:
apply(vec, 3, function(x) names(rev(sort(table(x))))[1])
#> [1] "c" "b" "a"
Created on 2022-02-03 by the reprex package (v2.0.1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Allan Cameron |
