Consider the following matrix:
MAT <- matrix(nrow=3,ncol=3,1:9)
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
I want to retrieve the row number if I provide a vector which exactly matches a row in MAT. So if I provide c(2,5,8), I should get back 2. I'm unsure how to accomplish this; the closest thing I know is using which to find the location of a single number in a matrix. An alternate could be a very slow quadruple for loop checking if the given vector matches a row in the matrix. Is there a one line solution for this problem?
You can use identical to test, apply loop and which to identify:
which(apply(MAT,1,function(x) identical(x,c(2L,5L,8L))))
[1] 2
Note that the values in the matrix are stored as integers, so you need to specify that in the vector to test.
You can apply a simple matching function to each row, then use which to find the row number:
search_vec = c(2, 5, 8)
vec_matches = apply(MAT, 1, function(row, search_vec) all(row == search_vec), search_vec)
row_num = which(vec_matches)
Related
Given an array of positions, for each row in a data frame. Fetch those elements in the most efficient way without using 'apply' functions.
Here's an example because I'm terrible at explaining. Given this matrix (or data frame):
A = matrix(1:9, nrow = 3, ncol = 3)
> A
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
Fetch the following elements from each column: 1, 3, 3
That means I want to fetch 1, 8 and 9. The first, third and third elements of each row.
I would expect that A[, c(1,3,3)] would do the trick. But it seems like I need to wrap it up in the diag function.
diag(A[, c(1,3,3)])
This looks like killing a fly with a nuke. It's extremely inefficient. I know there has to be a simple way to do this (without using apply or any of its family). Thanks in advance!
I would like to substitute a one-row vector for some of the rows of a matrix in R. Here is an example.
I would like to substitute the row "5,6" for the rows in A where the entries are 1. So, I would like to make "A" look like "A_goal"
The method I attempted (see the bottom line) was close, but it seems that it's writing "down the columns" instead of across the rows.
A=matrix(c(1,2,1,3,1,2,1,3),4,2)
B=matrix(c(5,6),1,2)
A_goal = matrix(c(5,2,5,3,6,2,6,3),4,2)
A
B
A_goal
# Here is an attempt that didn't work:
A[A==1]=B
A
Matrix indexing using {<- is done with column major ordering. So you will probably need to use apply on a row basis. This is essentially a for-loop over the rows of A. You also will need to transpose since apply will also deliver the results as columns:
t(apply(A, 1, function(x) if(x[1]==1){B}else{x}))
[,1] [,2]
[1,] 5 6
[2,] 2 2
[3,] 5 6
[4,] 3 3
If you were only intending the replacement to occur where the row was c(1,1) then the logical test would need to be modified to x == c(1,1)
The R language doesn't allow vectors to be variables. Why it is missing the feature? it would be nice my data frame with following features have something like this:
X1 X2
1. [1,2,3] [2,3,4] <br>
2. .... ....
I tried df <- as.data.frame(c(1,2,3),c(1,2,3)) but keep getting 3 rows created with numeric type instead I want a single row with vector type
Use an array:
array(rbind(1:3, 2:4), dim = c(1, 2, 3))
#, , 1
#
# [,1] [,2]
#[1,] 1 2
#
#, , 2
#
# [,1] [,2]
#[1,] 2 3
#
#, , 3
#
# [,1] [,2]
#[1,] 3 4
R does not allow to work with row data types u can have column data types. Each column can be a separate data type vector. You are not thinking the 'R' way. This short coming as you are putting it, is the strength of R. You can use an Array as suggested in the previous answer, if you strictly want to follow your chain of thought. Or just try to see how you can do what you want to do in 'R'. Rather than try to impose your known language to R.
How can produce a matrix where the entries are, say, the product of the index of the row and column. For example:
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 2 4 6
[3,] 3 6 9
NB: this is not specific to multiplication. I actually need it to raise each entry to a power (row index - column index), and was looking to not have to induce loops (as I suspect there is a more R-friendly way).
Thanks!
M <- matrix(NA, 3,3)
Mrcprod <- row(M)*col(M)
Use the outer product of 1:3 and 1:3
outer(1:3,1:3)
# or
1:3 %o% 1:3
If you need the different of the row indices and column indices, use outer again
outer(1:3,1:3,"-")
I am trying to create an index vector for a programming problem. The idea is to be able to index the elements of a matrix so I can replace just these elements with another matrix.
nstks<- 2
stk<-1:nstks
nareas<-3
area<-1:nareas
eff<-c(10,10,10)
x<-matrix(1:6,nrow=nstks,ncol=nareas)
h<-matrix(0,nrow=length(eff)+nstks,ncol=nareas)
for(i in 1:nareas) h[i,i]<-1
This returns a 5 by 3 matrix with 1s on the diagonal of the first 3 rows. Now I want to replace the 4th and 5th rows with a 2 by 3 matrix returned by another function. One way I figured is to index the h matrix by:
hlen<-c(nareas + stk,(nareas+ stk +(nareas +nstks)),(nareas+stk +(nareas+nstks)+(nareas+nstks)))
h[hlen] <- x
This replaces the 4,5,9,10,14,15th elements of h with the elements of x in order.
However, I need to make this flexible for differing numbers of nstks and nareas. As an example, for nareas=4 and nstks=3, I need to spit out a vector: c(5,6,7,12,13,14,19,20,21,26,27,28)
To clarify: I need to create the jacobian matrix for a constrained optimization problem. The dimensions of the jacobian vary depending on the number of constraints, and number of variables. I want to write a function that will give the jacobian matrix for any specified number of dimensions.
The variable is eff, which has the same length as nareas. There are non-negativity constraints on eff, which are reflected in the first nareas*nareas sub matrix being a diagonal identity matrix. The last rows of the matrix reflect the constraint on the number of fish that can be caught, by stock. So, for one stock, there will only be 1 additional row, 2 stocks, 2 additional rows etc. etc.
I need to replace the elements in these last rows by the elements given by another matrix. In the example, x is just for illustration. The actual x is given by a function but will have these same dimensions. Does this clarify things?
Any ideas?
Thanks!
I believe I can use:
h[(length(eff)+1): (length(eff)+nstks),1:nareas]<-x
I was making it too complicated as usual. Thanks for the help.
Instead of trying to find the indices for the values you need to replace with a sub-matrix returned from another function, can you not just place in the sub-matrix directly?
E.g. if you have:
x <- matrix(c(0, 1, 1, 0, 0, 1), ncol=3)
x
[,1] [,2] [,3]
[1,] 0 1 0
[2,] 1 0 1
Identify the part of h you want to drop the sub-matrix in:
h[4:5, 1:3] <- x
h
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1
[4,] 0 1 0
[5,] 1 0 1
Or, if x is a vector,
x <- c(0, 1, 1, 0, 0, 1)
x <- matrix(x, ncol=3, byrow=TRUE)
h[4:5, 1:3] <- x