Home > other >  a function that pick up rows by their name and makes another matrix in R
a function that pick up rows by their name and makes another matrix in R

Time:10-09

Say I have two Matrices A and B. Matrix A has only 100 rows and 1 column. Matrix B has 4000 rows and 1 column.

I want to write a function that takes rows(from 1 to 100) by their name from Matrix A, find it in B and then make another matrix C with row name with two columns Value of Matrix A and value of B. How is this possible?

CodePudding user response:

I understand you want a new matrix C containing only matching row names from A and B. Even though you said a merge would not work, an inner join would.

#Cretaing sample matrices
set.seed(123)
A <- matrix(runif(100), nrow = 100)
rownames(A) <- sample(1:5000, 100)

B <- matrix(runif(4000), nrow = 4000)
rownames(B) <- sample(1:5000, 4000)

#load needed libraries
library(tidyverse)
#move rownames to first column
A <- rownames_to_column(as.data.frame(A))
B <- rownames_to_column(as.data.frame(B))

#proceed to create 
C <- inner_join(A , B, by = "rowname")

#back to matrix
C <- matrix(as.numeric(unlist(C)),nrow=nrow(C))

#Move 1st column back to rownames
rownames(C) <- C[,1]
C <- C[,-1]

head(C)

The last line gives us that :

          [,1]      [,2]
1006 0.2875775 0.1379669
2585 0.7883051 0.2348300
2339 0.4089769 0.7531101
1448 0.8830174 0.2871001
3952 0.9404673 0.6626050
3358 0.0455565 0.6668502

CodePudding user response:

Maybe I understand your question wrong, but do you want to join both?

A <- data.frame(sample(1:10), row.names = LETTERS[1:10])
B <- data.frame(sample(1:20), row.names = LETTERS[4:23])


merge(A,B, by=0)

  •  Tags:  
  • r
  • Related