Matrix multiplication and addition in R - r

Perhaps I am not using the right terms in my search, but I was wondering if anyone could point out an easy way of doing the following:
I have two matrices:
mat1 = matrix(1:12, 3)
mat2 = matrix(c(1, 2, 1, 2, 3, 2, 1, 2), 2, 4)
I want to multiply each of row in a certain column of mat1 by the first row of mat2. For example, column 3 of mat1 would become (7*3, 8*3, 9*3)=(21, 24, 27). After this, I want to add the second row of mat2 to each row in a certain column of mat1, so the column 3 would become (21+2, 24+2, 27+2) = (23, 26, 29).

You can try the code below
t(t(mat1)*mat2[1,]+mat2[2,])
such that
> t(t(mat1)*mat2[1,]+mat2[2,])
[,1] [,2] [,3] [,4]
[1,] 3 6 23 12
[2,] 4 7 26 13
[3,] 5 8 29 14

Related

Sample without replacement x number of times from a vector

I have a vector c(1,2,3,4,5,6,7,8,9,10,11). I want to draw a sample of N = 2, 5 times from this vector without replacement; I would like to save the results from each selection in a separate column.
The output could look like this:
structure(c(1, 2, 3, 9, 7, 10, 4, 8, 5, 6), dim = c(2L, 5L)).
matrix with two rows and five columns.
matrix(sample(x), nrow=2, ncol=5)
# [,1] [,2] [,3] [,4] [,5]
# [1,] 5 7 4 8 2
# [2,] 3 10 9 1 6
Something like the following:
set.seed(7*11*13)
x <- c(1,2,3,4,5,6,7,8,9,10,11)
result <-matrix(as.numeric(NA), 2, 5)
for (i in 1:5) result[,i] <-
sample(x, 2, replace=FALSE)

How to multiply a matrix by a column in another data set? [duplicate]

This question already has answers here:
Fastest way to multiply matrix columns with vector elements in R
(6 answers)
Closed 3 years ago.
I am a beginner and now I faced a problem, I think it should have a very easy solution. Thank you for your help.
I have a matrix 313*442
each column should multiply with a fixed number in a separate column in the other data set.
Column one should multiply by 0.8, column two should multiply by -2.3 and ... and at the end, the sum of the row should calculate.
in final I should have one column that should correspond to each row.
An option would be to replicate the column in the second dataset to make the lengths same and multiply with the matrix
m1 * df1$v1[col(m1)]
# [,1] [,2]
#[1,] 2 9
#[2,] 4 12
Or another option is sweep
sweep(m1, 2, df1$v1, `*`)
# [,1] [,2]
#[1,] 2 9
#[2,] 4 12
data
m1 <- matrix(c(1, 2, 3, 4), ncol = 2)
df1 <- data.frame(v1 = c(2, 3))
Assuming that m1 is your matrix and v1 the vector with the values to be multiplied by each column. Then,
m1 <- matrix(c(1, 2, 3, 4), ncol = 2)
m1
[,1] [,2]
[1,] 1 3
[2,] 2 4
v1 <- c(2, 3)
t(t(m1) * v1)
# [,1] [,2]
#[1,] 2 9
#[2,] 4 12

How to compare single values of a vector with matrix and if they occur take values from another matrix with the same position?

I'm a programming beginner and I'm not able to solve this problem:
I have a vector length 132 and two matrices A and B with the size of 132x24. I would like to take every single value of the vector and compare it rowwise with matrix A. If the value occurs in A I want to have the index of the column to go to matrix B and pick the value from the column with the same position (row and column indices) as in matrix A. The results should be given back as a vector with the same length of 132.
How to do this? Do I need a for loop or are there some smart ways to work with packages?
Unfortunately I can not give example data.
Thank you for your help!
# vector v contains values that I want to compare with matrix A
> v
[1] 5 1 10 1 7
# every single value of v occurs in every row of A only once
# I want to have the position of this value in matrix A
> A
[,1] [,2] [,3] [,4]
[1,] 5 7 4 1
[2,] 14 1 3 3
[3,] 13 3 1 10
[4,] 2 1 5 8
[5,] 13 2 5 7
# the position in matrix A equals the position in matrix B
# now the values of B have to be returned as a vector
> B
[,1] [,2] [,3] [,4]
[1,] 6 3 4 3
[2,] 5 2 5 5
[3,] 4 6 3 1
[4,] 3 6 1 5
[5,] 2 4 6 3
# vector with fitting values of B
> x
[1] 6 2 1 6 3
v <- c(5, 1, 10, 1, 7)
A <- matrix(c(
5, 7, 4, 1,
14, 1, 3, 3,
13, 3, 1, 10,
2, 1, 5, 8,
13, 2, 5, 7), 5, byrow = TRUE)
B <- matrix(c(
6, 3, 4, 3,
5, 2, 5, 5,
4, 6, 3, 1,
3, 6, 1, 5,
2, 4, 6, 3), 5, byrow = TRUE)
myfun <- function(i) which(v[i]==A[i,])
ii <- 1:length(v)
B[cbind(ii, sapply(ii, myfun))]
The function myfun() is quick'n'dirty.
To test if your data are ok you can calculate how often the value v[i] is found in the row A[i,]
countv <- function(i) sum(v[i]==A[i,])
all(sapply(ii, countv)==1) ### should be TRUE
If you get FALSE then inspect:
which(sapply(ii, countv)!=1)
Alright, I'm not sure how you pictured your output, but I've got something that comes near.
Example data:
x <- 1:132
set.seed(123)
A <- matrix(sample(1:1000, size = 132*24, replace = TRUE), nrow = 132, ncol = 24)
B <- matrix(rnorm(132*24), nrow = 132, ncol = 24)
Now we check for every value of vector x if and where it occurs in every row of matrix A:
x.vs.A <- sapply(x, function(x){
apply(A, 1, function(y) {
match(x, y)
})
})
This gives us a matrix x.vs.A with 132 rows (the rows of A) and 132 columns (the values of x). Within the cells of this matrix, we will find either NA, if the combination of one value of x and one row of A was unsuccessful, or the column position within A of the FIRST match of the value of x.
And now we extract the rowwise position and bind them together with the cell value, depiting the second (column) dimension of the matched value. Thus we create for every value of x a matrix of row/column position of matches in matrix A:
x.in.A <- apply(x.vs.A, 2, function(x) cbind(which(!is.na(x)), x[!is.na(x)]))
Example:
> x.in.A[[1]]
[,1] [,2]
[1,] 12 17
[2,] 42 17
[3,] 73 12
[4,] 123 21
This would show that the first value in vector x can be found in A[12, 17], in A[42, 17] and so on.
Now access these values in B, returning vectors for each value of x, and bind them to the matrices in the list:
x.in.B <- lapply(x.in.A, function(x){
apply(x, 1, function(y){
B[y[1], y[2]]
})
})
x.in.AB <- mapply(function(x, y) cbind(x, y),
x.in.A, x.in.B)
> x.in.AB[[1]]
y
[1,] 12 17 -0.2492526
[2,] 42 17 -0.7985330
[3,] 73 12 0.1253824
[4,] 123 21 -0.9704919

Selecting rows conditional on column value from multiple matrices

I have
mat1 = matrix(c(2, 4, 3, 6, 7, 8), nrow=2, ncol=3)
mat2 = matrix(c(5, 6, 7, 1, 2, 3), nrow=2, ncol=3)
mat3 = matrix(c(8, 5, 8, 6, 7, 9), nrow=2, ncol=3)
which gives me 3 matrices:
[,1] [,2] [,3]
[1,] 2 3 7
[2,] 4 6 8
[,1] [,2] [,3]
[1,] 5 7 2
[2,] 6 1 3
[,1] [,2] [,3]
[1,] 8 8 7
[2,] 5 6 9
What I would like to do is compare the three matrices per row per first column, and select the row of the matrix that has the highest value on the first column.
For example: in row 1 column 1, matrix3 has the highest value (8) compared to matrix1 (2) and matrix2 (5). In row 2 column 1, matrix2 has the highest value (6). I would like to create a new matrix that copies the row of the matrix that has that highest value, resulting in:
[,1] [,2] [,3]
[1,] 8 8 7 <- From mat3
[2,] 6 1 3 <- From mat2
I know how to get a vector with the highest values from column 1, but I cannot get the whole row of the matrix copied into a new matrix. I have:
mat <- (mat1[1,])
which just copies the first row of the first matrix
[1] 2 3 7
I can select which number is the maximum number:
max(mat1[,1],mat2[,1],mat3[,1])
[1] 8
But I cannot seem to combine the two to return a matrix with the whole row.
Getting the code to loop for each row will be no problem, but I cannot seem to get it to work for the first row and as such, I am missing the essential code. Any help would be greatly appreciated. Thank you.
Are you working interactively? Do you manipulate multiple matrices spread in your workspace? A straightforward answer to your problem could be:
#which matrices have the largest element of column 1 in each row?
max.col(cbind(mat1[, 1], mat2[, 1], mat3[, 1]))
#[1] 3 2
rbind(mat3[1, ], mat2[2, ]) #use the above information to get your matrix
# [,1] [,2] [,3]
#[1,] 8 8 7
#[2,] 6 1 3
On a more ganeral use-case, a way could be:
mat_ls = list(mat1, mat2, mat3) #put your matrices in a "list"
which_col = 1 #compare column 1
which_mats = max.col(do.call(cbind, lapply(mat_ls, function(x) x[, which_col])))
do.call(rbind, lapply(seq_along(which_mats),
function(i) mat_ls[[which_mats[i]]][i, ]))
# [,1] [,2] [,3]
#[1,] 8 8 7
#[2,] 6 1 3
Probably not the prettiest solution
temp <- rbind(mat1, mat2, mat3)
rbind(temp[c(T,F),][which.max(temp[c(T,F),][, 1]),],
temp[c(F,T),][which.max(temp[c(F,T),][, 1]),])
## [,1] [,2] [,3]
## [1,] 8 8 7
## [2,] 6 1 3
You may also try:
a2 <- aperm(simplify2array( mget(ls(pattern="mat"))),c(3,2,1)) #gets all matrices with name `mat`
t(sapply(1:(dim(a2)[3]), function(i) {x1 <- a2[,,i]; x1[which.max(x1[,1]),]}))
# [,1] [,2] [,3]
#[1,] 8 8 7
#[2,] 6 1 3

Combinatorics R

I have a problem I think best can be solved using cominatorics.
Lets say you have values 4 values (2,5,6,7). I would like to get all vectors where I pick out 3 of them, that is I would like a matrix with (2,5,6),(2,5,7),(5,6,7). I would like to do this with a general vector. How do I do it?
x <- c(2, 5, 6, 7)
combn(x, 3)
gives
> combn(x, 3)
[,1] [,2] [,3] [,4]
[1,] 2 2 2 5
[2,] 5 5 6 6
[3,] 6 7 7 7
I have created a package iterpc which is able to solve most of the combination/permutation related problems.
library(iterpc)
x <- c(2, 5, 6, 7)
# combinations
getall(iterpc(4, 3, label=x))
# combinations with replacement
getall(iterpc(4, 3, replace=TRUE, label=x))
# permutations
getall(iterpc(4, 3, label=x, ordered=TRUE))

Resources