我想创建一个矩阵,在打印时仅出现在矩阵的“框架”。下面简单的代码来创建一个方阵
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,] * * * *
谢谢
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,] * * * * *
尝试别的东西:
noquote(matrix_maker())
Number of rows and columns: 4
[,1] [,2] [,3] [,4]
[1,] * * * *
[2,] * *
[3,] * *
[4,] * * * *
你可以通过你的矩阵的内部设置为“”这样做
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)
}
作为@大卫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
}