Avi
Avi

Reputation: 2283

Renumbering matrix column names in R

I have the following c matrix:

         [,1] [,2] [,3] [,4] [,5] [,6] 
result.1   62   64   44   55   81   66 
result.2   65   50   56   79   69   52 
result.3   57   62   84   76   65   59 
result.4   30   70   61   41   36   60 
result.6   66   63   51   44   66   28 
result.7   80   72   72   82   67   66 

The input is a matrix c. In the matrix there can be more than one gap (missing rows numbers) and the re-numeration would be for every gap from the first line to the last line.

As can be seen there is missing row (result.5) I would like to renumber the names of columns so that it will skip the missing value in the rows. The expected result will be:

        [,1] [,2] [,3] [,4] [,6] [,7] 
result.1   62   64   44   55   81   66 
result.2   65   50   56   79   69   52 
result.3   57   62   84   76   65   59 
result.4   30   70   61   41   36   60 
result.6   66   63   51   44   66   28 
result.7   80   72   72   82   67   66 

For reproducing the example, I add the following code:

c<-read.table (text = "
  [,1] [,2] [,3] [,4] [,5] [,6] 
  result.1   62   64   44   55   81   66 
  result.2   65   50   56   79   69   52 
  result.3   57   62   84   76   65   59 
  result.4   30   70   61   41   36   60 
  result.6   66   63   51   44   66   28 
  result.7   80   72   72   82   67   66 ", header = TRUE)
  setnames(c, c("[,1]", "[,2]", "[,3]", "[,4]", "[,5]", "[,6]"))
  c<-as.matrix (c)

Upvotes: 1

Views: 220

Answers (1)

Sotos
Sotos

Reputation: 51582

You can use the following,

colnames(c) <- gsub('\\D', '', rownames(c))
 c
#          1  2  3  4  6  7
#result.1 62 64 44 55 81 66
#result.2 65 50 56 79 69 52
#result.3 57 62 84 76 65 59
#result.4 30 70 61 41 36 60
#result.6 66 63 51 44 66 28
#result.7 80 72 72 82 67 66

Upvotes: 2

Related Questions