0
votes

I am trying to match the matrix column names with the names of the numeric vector and store the values of numeric vector into the matrix.

For example:

ex <-matrix(0,nrow=5, ncol= 2200)
colnames(ex) = paste("X",1:ncol(ex),sep="")
vec<- c(1:20)
names(vec) = c( "X13" , "X25", "X58", "X79", "X95" , "X118", "X212", "X311",    
"X422" , "X536", "X899", "X1005","X1080" , "X1118", "X1322", "X1516","X1705" 
, "X1890", "X1925", "X2008")

In the above code i want vec (numeric) to be copied into ex (matrix) by matching the corresponding column names. I have tried but i am not getting the solution as i am still new to R.

1

1 Answers

1
votes
# loop through column name of matrix that have correspondences in your vector   
for(i in colnames(ex)[colnames(ex) %in% names(vec)]) {
  # fill these matrix columns with the designated values from your vector
  ex[ , i] <- vec[i]
}