Scalar Multiplication in R - r

I'm trying to perform simple scalar multiplication in R, but I'm running into a bit of an issue.
In linear algebra I would do the following:
Here's how I've implemented this in R:
A <- matrix(1:4, 2, byrow = TRUE)
c <- matrix(rep(3, 4), 2)
A * c
This produces the correct output, but creating the scalar matrix c will be cumbersome when it comes to larger matrices.
Is there a better way to do this?

In R the default is scalar. For matrix multiplication use %*%. t is transpose and solve will give you the inverse. Here are some examples:
a = matrix(1:4,2,2)
3 * a
c(1:2) %*% a
c(1:2) %*% t(a)
solve(a)
Here is a link: matrix algebra in R

Use the function drop() to convert a 1x1 variable matrix into a "real" scalar. So you can write drop(c)*A and you don't need to replace c with the value itself.

Related

chol2inv(chol(x)) and solve(x)

I assumed that chol2inv(chol(x)) and solve(x) are two different methods that arrive at the same conclusion in all cases. Consider for instance a matrix S
A <- matrix(rnorm(3*3), 3, 3)
S <- t(A) %*% A
where the following two commands will give equivalent results:
solve(S)
chol2inv(chol(S))
Now consider the transpose of the Cholesky decomposition of S:
L <- t(chol(S))
where now the results of the following two commands do not give equivalent results anymore:
solve(L)
chol2inv(chol(L))
This surprised me a bit. Is this expected behavior?
chol expects (without checking) that its first argument x is a symmetric positive definite matrix, and it operates only on the upper triangular part of x. Thus, if L is a lower triangular matrix and D = diag(diag(L)) is its diagonal part, then chol(L) is actually equivalent to chol(D), and chol2inv(chol(L)) is actually equivalent to solve(D).
set.seed(141339L)
n <- 3L
S <- crossprod(matrix(rnorm(n * n), n, n))
L <- t(chol(S))
D <- diag(diag(L))
all.equal(chol(L), chol(D)) # TRUE
all.equal(chol2inv(chol(L)), solve(D)) # TRUE

Multiplicating a matrix with a vector results in a matrix

I have a document-term matrix:
document_term_matrix <- as.matrix(DocumentTermMatrix(corpus, control = list(stemming = FALSE, stopwords=FALSE, minWordLength=3, removeNumbers=TRUE, removePunctuation=TRUE )))
For this document-term matrix, I've calculated the local term- and global term weighing as follows:
lw_tf <- lw_tf(document_term_matrix)
gw_idf <- gw_idf(document_term_matrix)
lw_tf is a matrix with the same dimensionality as the document-term-matrix (nxm) and gw_idf is a vector of size n. However, when I run:
tf_idf <- lw_tf * gw_idf
The dimensionality of tf_idf is again nxm.
Originally, I would not expect this multiplication to work, as the dimensionalities are not conformable. However, given this output I now expect the dimensionality of gw_idf to be mxm. Is this indeed the case? And if so: what happened to the gw_idf vector of size n?
Matrix multiplication is done in R by using %*%, not * (the latter is just element-wise multiplication). Your reasoning is partially correct, you were just using the wrong symbols.
About the matrix multiplication, a matrix multiplication is only possible if the second dimension of the first matrix is the same as the first dimensions of the second matrix. The resulting dimensions is the dim1 of first matrix by the dim2 of the second matrix.
In your case, you're telling us you have a 1 x n matrix multiplied by a n x m matrix, which should result in a 1 x m matrix. You can check such case in this example:
a <- matrix(runif(100, 0 , 1), nrow = 1, ncol = 100)
b <- matrix(runif(100 * 200, 0, 1), nrow = 100, ncol = 200)
c <- a %*% b
dim(c)
[1] 1 200
Now, about your specific case, I don't really have this package that makes term-documents (would be nice of you to provide an easily reproducible example!), but if you're multiplying a nxm matrix element-wise (you're using *, like I said in the beginning) by a nx1 array, the result does not make sense. Either your variable gw_idf is not an array at all (maybe it's just a scalar) or you're simply making a wrong conclusion.

Compute the null space of a sparse matrix

I found the function (null OR nullspace) to find the null space of a regular matrix in R, but I couldn't find any function or package for a sparse matrix (sparseMatrix).
Does anybody know how to do this?
If you take a look at the code of ggm::null, you will see that it is based on the QR decomposition of the input matrix.
On the other hand, the Matrix package provides its own method to compute the QR decomposition of a sparse matrix.
For example:
require(Matrix)
A <- matrix(rep(0:1, 3), 3, 2)
As <- Matrix(A, sparse = TRUE)
qr.Q(qr(A), complete=TRUE)[, 2:3]
qr.Q(qr(As), complete=TRUE)[, 2:3]

making matrix with eigenvalues

I am trying to make a diagonal matrix of eigenvalues.
Here is my code:
E = eigen(cor(A))
VAL = E$values
VEC = E$vectors
so I get a vector with eigenvalues, but how do I turn it into a matrix.
I guess I can just use cbind() and manually input a e-value matrix, but there has to be a more correct way
You can use diag:
diag(E$values)

How to check if a matrix has an inverse in the R language

How do you determine if a matrix has an inverse in R?
So is there in R a function that with a matrix input, will return somethin like:
"TRUE" (this matrix has inverse)/"FALSE"(it hasn't ...).
Using abs(det(M)) > threshold as a way of determining if a matrix is invertible is a very bad idea. Here's an example: consider the class of matrices cI, where I is the identity matrix and c is a constant. If c = 0.01 and I is 10 x 10, then det(cI) = 10^-20, but (cI)^-1 most definitely exists and is simply 100I. If c is small enough, det() will underflow and return 0 even though the matrix is invertible. If you want to use determinants to check invertibility, check instead if the modulus of the log determinant is finite using determinant().
You can try using is.singular.matrix function from matrixcalc package.
To install package:
install.packages("matrixcalc")
To load it:
library(matrixcalc)
To create a matrix:
mymatrix<-matrix(rnorm(4),2,2)
To test it:
is.singular.matrix(mymatrix)
If matrix is invertible it returns FALSE, and if matrix is singlar/non-invertible it returns TRUE.
#MAB has a good point. This uses solve(...) to decide if the matrix is invertible.
f <- function(m) class(try(solve(m),silent=T))=="matrix"
x <- matrix(rep(1,25),nc=5) # singular
y <- matrix(1+1e-10*rnorm(25),nc=5) # very nearly singular matrix
z <- 0.001*diag(1,5) # non-singular, but very smalll determinant
f(x)
# [1] FALSE
f(y)
# [1] TRUE
f(z)
# [1] TRUE
In addition to the solution given by #josilber in the comments (i.e. abs(det(M)) > 1e-10) you can also use solve(M) %*% M for a square matrix or ginv in the MASS package will give the generalized inverse of a matrix.
To get TRUE or FALSE you can simply combine any of those methods with tryCatch and any like this:
out <- tryCatch(solve(X) %*% X, error = function(e) e)
any(class(out) == "error")

Resources