sacvf
sacvf

Reputation: 2533

How to search and extract values based on file names in R?

I have a matrix A that contain values. I have other 24 matrices where the names of the them are:

the name of A1 is data-00.img , the name of A2 is data-01.img, the name of A3 is data-02.img.........the name of A24 is data-23.img

What I want to do is to look at the first value in A if NA,return NA but if there is a value for example 12, search in the names of the other matrices (should be data-12.img) and then extract the corresponding value and put it instead of the 12 value in A.finally, do the same for all values in A.

Any help is appreciated!

 A = matrix( c(2, 4, 3, 1, 5, 7), nrow=2,ncol=3, byrow = TRUE) 

A1 = matrix( c(3, 6, 3, 1, 9, 7), nrow=2,ncol=3, byrow = TRUE) 
A2 = matrix( c(2, 3, 3, 1, 8, 3), nrow=2,ncol=3, byrow = TRUE) 
A3 = matrix( c(2, 9, 3, 1, 5, 7), nrow=2,ncol=3, byrow = TRUE) 
......
A24 = matrix( c(2,9, 3, 1, 7, 7), nrow=2,ncol=3, byrow = TRUE) 

Above I tried to give a reproducible example.

Upvotes: 1

Views: 56

Answers (1)

zx8754
zx8754

Reputation: 56149

Question is not very clear, I think this is what you need:

#dummy data
A = matrix( c(2, 4, NA, 1, 5, 7), nrow=2,ncol=3, byrow = TRUE) 

A1 = matrix( c(1:6), nrow=2,ncol=3, byrow = TRUE) 
A2 = matrix( c(7:12), nrow=2,ncol=3, byrow = TRUE) 
A3 = matrix( c(13:18), nrow=2,ncol=3, byrow = TRUE) 
A4 = matrix( c(19:24), nrow=2,ncol=3, byrow = TRUE) 
A5 = matrix( c(25:30), nrow=2,ncol=3, byrow = TRUE) 
A6 = matrix( c(31:36), nrow=2,ncol=3, byrow = TRUE) 
A7 = matrix( c(37:42), nrow=2,ncol=3, byrow = TRUE) 

#result
matrix(sapply(seq_along(A),
              function(i){
                if(is.na(A[i])) NA else
                get(paste0("A",A[i]))[i]
              }),
       nrow=2)

#      [,1] [,2] [,3]
# [1,]    7   20   NA
# [2,]    4   29   42

Upvotes: 2

Related Questions