r - 如何在 R 中将 Pin Pad 创建为矩阵?
问题描述
我正在研究一些机器人问题,我想以矩阵的形式创建一个 ATM Pin Pad
到目前为止我能想到的是
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 等等,直到行满,因为它们不会被考虑在图表中形成
示例:如果宽度为 3,我现在已经明确处理宽度 1 和 9 的情况,我需要类似的东西
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
推荐阅读
- javascript - 为什么这段代码写在 div 标签之间时会给我错误
- swift - 如何通过单击 menuItem 重新打开关闭的应用程序窗口
- html - 通过快速路线返回图像数据
- python - Flask reloader 在 Windows 上因“没有名为 Scripts\flask 的模块”而崩溃
- c++ - 合并的“位”-线程安全向量
- linux - 如何打印 /tmp 目录中每个文件的最后 20 行以外的所有行?
- reactjs - React-native 响应式字体大小
- php - 我的 PHP 站点在 apache 上本地运行,但是在启动 Heroku 时出现 PDO 连接错误
- reactjs - 我可以(或者我应该)在 React.js 中将 7-1 模式与 SASS 一起使用吗?
- python - TypeError:float() 参数必须是字符串或数字,而不是 'builtin_function_or_method'