vendredi 5 mai 2017

How can I write a for loop for a matrix based on conditions from another matrix?

I'm trying to get a new matrix based on conditions in another matrix. The original matrix (matrix 1) looks like this:

[empty] |V1     |V2     |V3    |V4    |V5    |....  |V17   | V18
1       |NA     |NA     |name1 |name2 |name3 |....  |name15|NA
2       |abc    |2016   |NA    |10    |20    |....  |NA    |name1
3       |abc    |2016   |NA    |10    |20    |....  |NA    |name2
4       |abc    |2016   |NA    |10    |20    |....  |NA    |name3
...     |abc    |2016   |NA    |10    |20    |....  |NA    |....
16      |abc    |2016   |NA    |10    |20    |....  |NA    |name15

What I'm trying to code is a new matrix (matrix 2) with the following condition: if the value of the first line of matrix 1 in the concerning column equals the value of the last column of matrix 1 in the concerning line, matrix 2 should write down the value that was originally in matrix 1 in the concerning cell; if the condition isn't true, it should write "NA". For example, in line 2, the fourth and the fifth column should be replaced by "NA", whereas in line 3, the fourth column should stay "10" and the fifth should be replaced by "NA". Here's what I've coded so far:

a<-seq(1:16)  
b<-seq(1:18)

matrix2<- matrix(nrow=16, ncol=18)

for(i in 1:dim(matrix2)[1]) {
 for(j in 1:dim(matrix2)[2]) {
  matrix2[i,j] = if("matrix1[a,b]"=="matrix1[a,18]") {"matrix1[a,b]"} else {"NA"}
  }
}
print(matrix2)

What is returned is a matrix with 16 rows and 18 columns containing "NA". I am almost sure that there's more than just one problem with my code. Also, in fact, the condition should only be applied for matrix1[2:16,3:17] but I don't have a clue how to write this. Thank you a lot for your help!

Aucun commentaire:

Enregistrer un commentaire