在R中字符串的每个第k个位置插入字符

I have a n x n square matrix where n is a perfect square. I would like to insert a vertical line at every k^th position where k is the square root of n and print the result using R.

I am able to achieve this most of the way, however I get a NULL at the end of each row.

这是我的代码

# create test matrix
set.seed(1)
temp = matrix(sample(x=(11:99), size= 81), 9, 9)

custom_print = function(x){

  s = as.integer(sqrt(nrow(x)))

  for(r in 1:nrow(x)){
      for(c in 1:s){
        current.row = cat("|", x[r, (s*(c-1)+1):(c*s)], "")
      }
    print(current.row)
  }
}

custom_print(temp)

结果为以下输出:

> custom_print(temp)
| 34 15 37 | 99 53 85 | 13 50 62 NULL
| 43 27 92 | 64 16 12 | 14 58 32 NULL
| 60 24 75 | 31 71 97 | 66 17 18 NULL
| 89 63 25 | 39 70 41 | 57 22 67 NULL
| 28 40 54 | 45 51 38 | 52 74 33 NULL
| 86 68 19 | 69 42 29 | 23 83 90 NULL
| 96 47 95 | 21 91 98 | 81 79 80 NULL
| 65 87 35 | 56 36 93 | 46 55 20 NULL
| 61 82 11 | 84 72 76 | 94 26 44 NULL

I don't know the reason that I can getting the NULL at the end of each row and I don't know how to remove it.

有人可以让我知道我在哪里出错吗?

评论