Skip to contents

Like matrix, this function creates a matrix from the given set of values. However, these values can also be represented by a character string, or a list of vectors. Initially inspired by NumPy's matrix function.

Usage

mat(x, ...)

# Default S3 method
mat(x, ...)

# S3 method for class 'character'
mat(x, rows = TRUE, sep = ",", eval = FALSE, ...)

# S3 method for class 'list'
mat(x, rows = TRUE, ...)

Arguments

x

A data vector, character string, or a list.

...

Additional optional arguments to be passed on to matrix.

rows

Logical. If TRUE (the default) the matrix is filled by rows, otherwise the matrix is filled by columns.

sep

Separator string. Values within each row/column of x are separated by this string. Default is ",".

eval

Logical indicating whether or not the character string contains R expressions that need to be evaluated. Default is FALSE. See examples below for usage.

Value

A matrix.

See also

Examples

# Creating a matrix from a character string
mat("1, 2, 3, 4; 5, 6, 7, 8") # ";" separates rows
#>      [,1] [,2] [,3] [,4]
#> [1,]    1    2    3    4
#> [2,]    5    6    7    8
mat("1, 2, 3, 4; 5, 6, 7, 8", rows = FALSE) # ";" separates columns
#>      [,1] [,2]
#> [1,]    1    5
#> [2,]    2    6
#> [3,]    3    7
#> [4,]    4    8
mat("1 2 3 4; 5 6 7 8", sep = "") # use spaces instead of commas
#>      [,1] [,2] [,3] [,4]
#> [1,]    1    2    3    4
#> [2,]    5    6    7    8
mat(c(1, 2, 3, 4, 5, 6, 7, 8), nrow = 2, byrow = TRUE) # works like matrix too
#>      [,1] [,2] [,3] [,4]
#> [1,]    1    2    3    4
#> [2,]    5    6    7    8

# Character strings containing R expressions
mat("rnorm(3); rnorm(3)")
#>      [,1]      
#> [1,] "rnorm(3)"
#> [2,] "rnorm(3)"
mat("rnorm(3); rnorm(3)", eval = TRUE)
#>            [,1]        [,2]       [,3]
#> [1,]  1.0673079  0.07003485 -0.6391233
#> [2,] -0.0499649 -0.25148344  0.4447971
mat("1, 2, 3; 4, 5, pi")
#>      [,1] [,2] [,3]
#> [1,] "1"  "2"  "3" 
#> [2,] "4"  "5"  "pi"
mat("1, 2, 3; 4, 5, pi", eval = TRUE)
#>      [,1] [,2]     [,3]
#> [1,]    1    2 3.000000
#> [2,]    4    5 3.141593
mat("-1, -.1; -0.1, -1.0")
#>      [,1] [,2]
#> [1,] -1.0 -0.1
#> [2,] -0.1 -1.0

# Creating a matrix from a list
z1 <- list(1:5, 6:10)
z2 <- list(a = 1:5, b = 6:10)
mat(z1)
#>      [,1] [,2] [,3] [,4] [,5]
#> [1,]    1    2    3    4    5
#> [2,]    6    7    8    9   10
mat(z2) # preserves names as row names
#>   [,1] [,2] [,3] [,4] [,5]
#> a    1    2    3    4    5
#> b    6    7    8    9   10
mat(z2, rows = FALSE) # preserves names as column names
#>      a  b
#> [1,] 1  6
#> [2,] 2  7
#> [3,] 3  8
#> [4,] 4  9
#> [5,] 5 10