创建一个矩阵,以便在打印时显示为“ *”框架。 R项目

时间:2019-02-10 09:39:38

标签: r matrix

我正在尝试创建一个矩阵,该矩阵在打印时仅出现在矩阵的“框架”中。在简单的代码下面创建方矩阵

matrix_maker <- function() {

 x <- as.integer(readline("Number of rows and columns: "))

 matrix(data = '*',
     nrow = x,
     ncol = x)
 }

打印结果必须是这样的:

       [,1] [,2] [,3] [,4] 
   [1,] *     *    *    *
   [2,] *               * 
   [3,] *               * 
   [4,] *     *    *    *

谢谢

2 个答案:

答案 0 :(得分:1)

您可以通过将矩阵内部设置为“”来实现此目的

matrix_maker <- function() {
  x <- as.integer(readline("Number of rows and columns: "))
  y <- matrix(data = '*', nrow = x, ncol = x)
  if(x > 2){
    y[2:(nrow(y)-1), 2:(ncol(y)-1)] <- ""
  }
  return(y)
}

正如@David Arenburg指出的那样,另一种选择是将整个矩阵设置为“”,然后将框架设置为“ *”。

matrix_maker <- function() {
  x <- as.integer(readline("Number of rows and columns: "))
  y <- matrix(data = '', nrow = x, ncol = x)
  y[row(y) %in% c(1,x) | col(y) %in% c(1,x)] <- "*"
  y
}

答案 1 :(得分:1)

[]

这样称呼:

matrix_maker <- function() {
 y<-noquote("*")
  x <- as.integer(readline("Number of rows and columns: "))
  m<-matrix(data = y,
         nrow = x,
         ncol = x)
  if(ncol(m)%in%c(0,1,2)) return(m)
 ifelse(ncol(m)%%2!=0,m[2:(nrow(m)-1),2:(nrow(m)-1)]<-" ",
        m[2:(nrow(m)-1),2:(ncol(m)-1)]<-" ")

  m
}

尝试其他方法:

 noquote(matrix_maker())

   Number of rows and columns: 5
     [,1] [,2] [,3] [,4] [,5]
[1,] *    *    *    *    *   
[2,] *                   *   
[3,] *                   *   
[4,] *                   *   
[5,] *    *    *    *    *