Learn R Programming

miraculix (version 0.9.23)

vector012matrix: multiplication from left of 012 vector with a matrix

Description

vector012matrix and matrixvector012 multiply a real-valued matrix from left and right with a vector that contains only the values \(0\),\(1\),\(2\), respectively. For larger matrices (greater than \(25\times 25\)) the functions are \(3\) to \(10\) times faster than the matrix multiplication %*%.

This function is not based on RFoptions()$genetics$snpcoding.

Usage

vector012matrix(v, M)
matrixvector012(M, v)

Arguments

v

an integer valued with values \(0\),\(1\),\(2\) only. Anything different from \(1\) and \(2\) is treated as \(0\).

M

a real-valued matrix whose size matches v

Value

The two function vector012matrix and matrixvector012 return a vector of length ncol(M) and nrow(M), respectively.

See Also

vectorGeno

relationshipMatrix

Examples

Run this code
# NOT RUN {
set.seed(0)

n <- 800
m <- 800

vl <- sample(0:2, m, replace = TRUE) 
vr <- sample(0:2, n, replace = TRUE)
M <- matrix(1 : (n * m), ncol=n) + 0.0

## v1 and v2 are the same
v1 <- M %*% vr
v2 <- matrixvector012(M, vr)
stopifnot(all(v1 == v2))

## v1 and v2 are the same
v1 <- vl %*% M 
v2 <- vector012matrix(vl, M)
stopifnot(all(v1 == v2))

## matrixvector012 is 3 to 15 times faster for larger matrices
N <- 1 + as.integer(100000000 / n^2)
print(system.time( for (i in 1:N) M %*% vr ))
print(system.time( for (i in 1:N) matrixvector012(M, vr) )) # much faster
# }
# NOT RUN {
<!-- %print(system.time( for (i in 1:N) -->
# }
# NOT RUN {
<!-- %  .Call(C_matrixvector012, M, vr) ## further 20\% faster for small matrix -->
# }
# NOT RUN {
<!-- %)) -->
# }
# NOT RUN {
## vector012matrix is 3 to 10 times faster for larger matrices
print(system.time(for (i in 1:N) vl %*% M ))
print(system.time( for (i in 1:N) vector012matrix(vl, M) )) # much faster
# }
# NOT RUN {
<!-- %print(system.time( for (i in 1:N) -->
# }
# NOT RUN {
<!-- %  .Call(C_vector012matrix, vl, M) ## further 20\% faster for small matrix -->
# }
# NOT RUN {
<!-- %)) -->
# }
# NOT RUN {
# }

Run the code above in your browser using DataLab