Personal code snippets of @tmasjc

Site powered by Hugo + Blogdown

Image by Mads Schmidt Rasmussen from unsplash.com

Minimal Bootstrap Theme by Zachary Betz

Compute by Matrix Column

Apr 10, 2018 #matrix

library(tidyverse)

# dummy data
mat <- matrix(rnorm(20 * 5, mean = 100, sd = sqrt(10)) %>% round(digits = 2), 20, 5)
mat
##         [,1]   [,2]   [,3]   [,4]   [,5]
##  [1,]  98.54  97.35  97.87 100.25 100.55
##  [2,] 104.57  99.15  97.69  97.38 105.13
##  [3,] 100.09 103.99 100.44 102.01  98.99
##  [4,] 100.24 101.53 100.89 100.07 101.49
##  [5,]  94.90  99.45  99.07 102.14  99.20
##  [6,] 109.11 101.44 100.49  99.05  98.97
##  [7,] 103.97 100.75 103.46 101.76 102.86
##  [8,]  98.33 101.89  95.85  99.83  97.05
##  [9,]  93.68  99.69  96.51 102.35 100.57
## [10,] 102.69  99.94  97.85 100.79 104.58
## [11,] 103.16 105.48 104.14  98.14  99.67
## [12,]  98.35 101.06  96.85 100.02  99.18
## [13,] 103.63  99.48 100.38 100.20 106.09
## [14,]  99.43  96.25 102.27 100.78  96.71
## [15,] 104.43  97.00  99.38 105.21  97.15
## [16,] 103.54 105.60  99.77 101.48  94.83
## [17,] 100.17 102.27  94.45  99.96 100.86
## [18,] 100.40  99.00  97.39 100.10  98.80
## [19,] 100.19  98.88 102.01 100.21  97.10
## [20,] 101.14  99.39 104.51  97.14 101.49
# find index by maximum value in a column
data_frame(
    column = 1:ncol(mat),
    row = apply(mat, 2, which.max)
)
## Warning: `data_frame()` is deprecated, use `tibble()`.
## This warning is displayed once per session.
## # A tibble: 5 x 2
##   column   row
##    <int> <int>
## 1      1     6
## 2      2    16
## 3      3    20
## 4      4    15
## 5      5    13