在R

时间:2016-04-26 09:00:30

标签: r matrix col

我有以下c矩阵:

         [,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 

输入是矩阵c。在矩阵中可能存在多个间隙(缺少行数),并且重新计算将是从第一行到最后一行的每个间隙。

可以看到缺少行(result.5)我想重新编号列的名称,以便它会跳过行中的缺失值。预期结果将是:

        [,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 

为了再现这个例子,我添加了以下代码:

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)

1 个答案:

答案 0 :(得分:2)

您可以使用以下内容

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
相关问题