我正在研究一些机器人问题,我想创建一个矩阵形式的 ATM 密码键盘
目前我能想到的是
items = 10;
width = 3;
x <- 1:9
length(x) <- prod(dim(matrix(x, ncol = width)))
## you will get a warning here unless suppressWarnings() is used except for width = 3
Pad = matrix(x, ncol = width, byrow = TRUE)
if(width == 1)
Pad = rbind(Pad, c(0))
if(width == 9)
Pad = cbind(Pad, c(0))`
我面临的问题是宽度可以是可变的数量,因此在末尾(9 之后)放置零会产生问题。另外,如果我以某种方式放置一个始终位于最后一行的零,那么 0 之后的任何内容都应该是 -1、-2 等等,直到该行已满,因为它们不会在图表中被考虑形成
示例: 我现在已经明确处理了宽度 1 和 9 的情况 如果宽度是 3 我需要类似的东西
1 2 3
4 5 6
7 8 9
0 -1 -2
如果宽度是4
1 2 3 4
5 6 7 8
9 0 -1 -2
如果宽度是5
1 2 3 4 5
6 7 8 9 0
如何在 R 中实现这一目标?
最佳答案
简单/小辅助函数:
mypad <- function(nrow, ncol) {
if (missing(nrow)) nrow <- ceiling(10L / ncol)
if (missing(ncol)) ncol <- ceiling(10L / nrow)
x <- c(1:9, 0L)
length(x) <- prod(nrow, ncol)
x[ is.na(x) ] <- -seq_len(sum(is.na(x)))
matrix(x, nrow = nrow, ncol = ncol, byrow = TRUE)
}
用途:
mypad(ncol=3)
# [,1] [,2] [,3]
# [1,] 1 2 3
# [2,] 4 5 6
# [3,] 7 8 9
# [4,] 0 -1 -2
mypad(ncol=4)
# [,1] [,2] [,3] [,4]
# [1,] 1 2 3 4
# [2,] 5 6 7 8
# [3,] 9 0 -1 -2
mypad(ncol = 3)
# [,1] [,2] [,3]
# [1,] 1 2 3
# [2,] 4 5 6
# [3,] 7 8 9
# [4,] 0 -1 -2
mypad(ncol = 4)
# [,1] [,2] [,3] [,4]
# [1,] 1 2 3 4
# [2,] 5 6 7 8
# [3,] 9 0 -1 -2
mypad(ncol = 5)
# [,1] [,2] [,3] [,4] [,5]
# [1,] 1 2 3 4 5
# [2,] 6 7 8 9 0
mypad(ncol = 6)
# [,1] [,2] [,3] [,4] [,5] [,6]
# [1,] 1 2 3 4 5 6
# [2,] 7 8 9 0 -1 -2
关于r - 如何在 R 中创建 Pin Pad 作为矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56708202/