-2

imagine you have a matrix of 2000 rows and 2000 columns in R. Both (rownames and column names are identical). Now I have another data frame with 380 rows and one column. I would like to know how it is possible to select the rows and columns from the big matrix which match to the 380 values? I hope you can help.

Best wishes,

Lukas

Luker354
  • 659
  • 3
  • 8
  • 1
    you could ``merge()`` your data or use the ``match()`` function. Please share your data and what you tried so far. – Gainz Feb 11 '20 at 20:08
  • I have already tried that one: matrix[(match(matrix, df2)),] – Luker354 Feb 11 '20 at 20:20
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. (Include a smaller data set than your own for testing) – MrFlick Feb 11 '20 at 20:25

1 Answers1

0

If I am understanding correctly, here is an example of how you could create a second column in the dataframe with the matching value from the matrix.

A<-matrix(c(1:16), nrow = 4)
colnames(A)<-c("a","b","c","d")
rownames(A)<-c("a","b","c","d")
b<-as.data.frame(matrix(c("a","b","c","d")))

for (i in 1:nrow(B)){
  b[i,2]<-A[b[i,1],b[i,1]]
}

b
Tanner33
  • 120
  • 2
  • 15
  • Thanks a lot for answering, but I want as output a matrix again, with the rows and the columns of the matched values. Do you know what I mean? – Luker354 Feb 11 '20 at 20:36
  • I may not be understanding. I thought you wanted the value from the cell of the matrix that has the column and row names that match the value in the cell of the dataframe. – Tanner33 Feb 11 '20 at 20:39
  • Are you saying you want to subset the original matrix to only include values that match the dataframe? – Tanner33 Feb 11 '20 at 20:44
  • `A<-matrix(c(1:16), nrow = 4)` `colnames(A)<-c("a","b","c","d")` `rownames(A)<-c("a","b","c","d")` `b<-as.data.frame(matrix(c("a","b","c")))` Use column one of dataframe to provide names of columns and rows you want from matrix A to be in matrix C. `C<-A[as.character(b[,1]),as.character(b[,1])]` – Tanner33 Feb 11 '20 at 20:49
  • Yes exactly, I only want to subset the original matrix to only include values that match the data frame. – Luker354 Feb 11 '20 at 21:36
  • This Should do it `Output<-Original_Matrix[as.character(Original_Dataframe[,1]),as.character(Original_Dataframe[,1])]`. – Tanner33 Feb 11 '20 at 21:48