使用 1:n 中的唯一值创建 n × n 矩阵

2024-01-08

我想在 R 中生成一个随机的 n × n 矩阵,离散值范围从 1 到 n。棘手的部分是我希望每个值在行和列中都是唯一的。

例如,如果n=3矩阵可能如下所示:

1 2 3 
2 3 1 
3 1 2 

或者它可能看起来像这样:

2 3 1 
1 2 3 
3 1 2 

有人知道如何生成这种矩阵吗?


你想要的叫做拉丁方 https://en.wikipedia.org/wiki/Latin_square。这是一个函数(来自R 食谱 http://www.cookbook-r.com/Tools_for_experiments/Generating_counterbalanced_orders/#a-function-for-generating-latin-squares;也可以看看here https://math.stackexchange.com/questions/63131/generate-random-latin-squares以及一堆其他在线搜索结果)允许生成它们:

latinsquare <- function(len, reps=1, seed=NA, returnstrings=FALSE) {

    # Save the old random seed and use the new one, if present
    if (!is.na(seed)) {
        if (exists(".Random.seed"))  { saved.seed <- .Random.seed }
        else                         { saved.seed <- NA }
        set.seed(seed)
    }

    # This matrix will contain all the individual squares
    allsq <- matrix(nrow=reps*len, ncol=len)

    # Store a string id of each square if requested
    if (returnstrings) {  squareid <- vector(mode = "character", length = reps) }

    # Get a random element from a vector (the built-in sample function annoyingly
    #   has different behavior if there's only one element in x)
    sample1 <- function(x) {
        if (length(x)==1) { return(x) }
        else              { return(sample(x,1)) }
    }

    # Generate each of n individual squares
    for (n in 1:reps) {

        # Generate an empty square
        sq <- matrix(nrow=len, ncol=len) 

        # If we fill the square sequentially from top left, some latin squares
        # are more probable than others.  So we have to do it random order,
        # all over the square.
        # The rough procedure is:
        # - randomly select a cell that is currently NA (call it the target cell)
        # - find all the NA cells sharing the same row or column as the target
        # - fill the target cell
        # - fill the other cells sharing the row/col
        # - If it ever is impossible to fill a cell because all the numbers
        #    are already used, then quit and start over with a new square.
        # In short, it picks a random empty cell, fills it, then fills in the 
        # other empty cells in the "cross" in random order. If we went totally randomly
        # (without the cross), the failure rate is much higher.
        while (any(is.na(sq))) {

            # Pick a random cell which is currently NA
            k <- sample1(which(is.na(sq)))

            i <- (k-1) %% len +1       # Get the row num
            j <- floor((k-1) / len) +1 # Get the col num

            # Find the other NA cells in the "cross" centered at i,j
            sqrow <- sq[i,]
            sqcol <- sq[,j]

            # A matrix of coordinates of all the NA cells in the cross
            openCell <-rbind( cbind(which(is.na(sqcol)), j),
                              cbind(i, which(is.na(sqrow))))
            # Randomize fill order
            openCell <- openCell[sample(nrow(openCell)),]

            # Put center cell at top of list, so that it gets filled first
            openCell <- rbind(c(i,j), openCell)
            # There will now be three entries for the center cell, so remove duplicated entries
            # Need to make sure it's a matrix -- otherwise, if there's just 
            # one row, it turns into a vector, which causes problems
            openCell <- matrix(openCell[!duplicated(openCell),], ncol=2)

            # Fill in the center of the cross, then the other open spaces in the cross
            for (c in 1:nrow(openCell)) {
                # The current cell to fill
                ci <- openCell[c,1]
                cj <- openCell[c,2]
                # Get the numbers that are unused in the "cross" centered on i,j
                freeNum <- which(!(1:len %in% c(sq[ci,], sq[,cj])))

                # Fill in this location on the square
                if (length(freeNum)>0) { sq[ci,cj] <- sample1(freeNum) }
                else  {
                    # Failed attempt - no available numbers
                    # Re-generate empty square
                    sq <- matrix(nrow=len, ncol=len)

                    # Break out of loop
                    break;
                }
            }
        }

        # Store the individual square into the matrix containing all squares
        allsqrows <- ((n-1)*len) + 1:len
        allsq[allsqrows,] <- sq

        # Store a string representation of the square if requested. Each unique
        # square has a unique string.
        if (returnstrings) { squareid[n] <- paste(sq, collapse="") }

    }

    # Restore the old random seed, if present
    if (!is.na(seed) && !is.na(saved.seed)) { .Random.seed <- saved.seed }

    if (returnstrings) { return(squareid) }
    else               { return(allsq) }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 1:n 中的唯一值创建 n × n 矩阵 的相关文章

  • 行对名称中具有特定模式的列求和

    我有一个像这样的数据表 DT lt ata table data table ref rep 3L 4L nb 12 15 i1 c 3 1e 05 0 044495 0 82244 0 322291 i2 c 0 000183 0 155
  • R,使用具有两种以上可能性的二项式分布

    我知道这可能是基本的 但我似乎有一个心理障碍 假设您想要计算在一个骰子上掷出 4 5 或 6 的概率 在 R 中 这很简单 sum 1 6 1 6 1 6 这给出了 1 2 这是正确答案 然而 我内心深处 可能应该保留的地方 认为我应该能够
  • 如何按定义的顺序将图像合并到一个文件中

    我有大约 100 张图像 png 我不想手动执行此操作 而是希望将它们按照定义的顺序 基于文件名 并排放置在一个 pdf 中 每行 12 个图像 有人有什么建议吗 我按照下面托马斯告诉我的方法尝试了 它把它们贴在旁边有一个黑边 我怎样才能去
  • MATLAB - 通过垂直连接子矩阵重新排列矩阵

    我在执行以下任务时遇到问题 假设一个 3x6 矩阵 A 0 2787 0 2948 0 4635 0 8388 0 0627 0 0435 0 6917 0 1185 0 3660 0 1867 0 2383 0 7577 0 6179 0
  • dplyr:连接中的 NSE (by)

    我很难弄清楚如何使用 dplyr left join 和 NSE 连接两个表 问题是我无法为 by 提供正确的值 我想我现在已经找到了解决方案 但感觉我正在以一种额外复杂的方式来做 因此 如果您知道更简单 更优雅的解决方案 请告诉我 这就是
  • 使用 Matrix.setPolyToPoly 选择位图上具有 4 个点的区域

    我正在 Android 上使用位图 在使用 4 个点选择位图上的区域时遇到问题 并非所有 4 点组都适合我 在某些情况下 结果只是一个空白位图 而不是裁剪后的位图 如图所示 并且 logcat 中没有任何错误 甚至是内存错误 这是我用来进行
  • R中IF函数的使用

    我正在短跑ifR 中的函数 但收到以下警告消息 In if runif 50 0 1 lt 0 69 the condition has length gt 1 and only the first element will be used
  • 使用点阵个性化 R 上显示的 X 轴值

    我收集了大量包含日期 客户端及其 NFS 使用情况的数据 我正在使用lattice R包进行绘图 正如对超级用户的建议 https superuser com questions 523195 plot custom log data on
  • R:如何将字符/数字转为1,NA转为0?

    有没有一种简单的方法可以将列的字符 数字变为 1 将 NA 变为 0 这里有一些示例数据 我想将其应用于 3 4 structure list Item Code c 176L 187L 191L 201L 217L 220L Item x
  • 平滑连续 2D 点

    UPDATE 感谢 user20650和 李哲源Zheyuan Li 这是我想出的解决方案 Example data set df 3600 observations points Create a vector of the cumula
  • 在网格中查找具有相同值的相邻单元格。想法如何改进这个功能?

    我是 Python 新手 学习了 1 个多月 我尝试创建 Tic Tac Toe 然而 一旦我完成了它 我决定扩展棋盘 从 3x3 到 9x9 具体取决于客户的输入 并通过在棋盘上的任意位置连接 4 个行 列或对角线来获胜 因此 我需要一个
  • R 中 SVG 图形的最佳设备? [关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 我想从 R 导出 SVG 图形 似乎有两种选择 RSvgDevice 和 Cairo 有人可以对这些包发表评论吗 是默认的还是明显比另一个
  • StatET调试工具

    我想我只是很密集 但我似乎无法弄清楚如何在 Eclipse 中的 R 中使用调试工具 StatET 插件 有人有关于这个主题的任何提示或教程吗 StatET 2 00 现在对高级 可视化调试提供实验性支持 需要 Eclipse 3 6 或
  • rvest 函数 html_nodes 返回 {xml_nodeset (0)}

    我正在尝试抓取以下网站的数据框 http stats nba com game 0041700404 playbyplay http stats nba com game 0041700404 playbyplay 我想创建一个表格 其中包
  • 在 Google Colab 上的 R 笔记本中安装 python 库

    我正在尝试在 Google Colab 上的 R 笔记本中安装 python 库 为此我使用 reticulate 包 library reticulate py install pandas 但我得到的结果是这个错误 Error coul
  • R 数据结构的运算效率

    我想知道是否有任何关于操作效率的文档R 特别是那些与数据操作相关的 例如 我认为向数据框添加列是有效的 因为我猜您只是向链接列表添加一个元素 我想添加行会更慢 因为向量保存在数组中C level你必须分配一个新的长度数组n 1并将所有元素复
  • 在闪亮的数据表中为每个单元格显示工具提示或弹出窗口?

    有没有什么方法可以为 r闪亮数据表中的每个单元格获取工具提示 有很多方法可以获取悬停行或列 但我找不到一种方法来获取行和列索引并为每个单元格显示不同的悬停工具提示 任何人都可以修改以下代码吗 library shiny library DT
  • 32 位应用程序的特征最大矩阵大小

    所以 我正在寻找Eigen http eigen tuxfamily org index php title Main Page当我尝试声明大于 10000x10000 的矩阵时 包崩溃 我需要声明一个像这样的矩阵 可靠地大约有 13000
  • R 中的数据框操作 - 将单元格向左移动并删除 NA

    我有一个数据框 其列由随机分布的值和 NA 组成 如下所示 a lt c S E NA S NA b lt c A NA M G K c lt c I NA NA NA L meh lt dataframe a b c 1 2 3 4 5
  • 闪亮井板宽度

    library shiny library shinydashboard ui lt dashboardPage dashboardHeader dashboardSidebar dashboardBody wellPanel tags d

随机推荐

  • Excel VBA - 日期格式转换

    我遇到了一项具有挑战性的任务 使用许多解决方法都无法解决该任务 在一列中我有日期 日期可以采用以下三种格式 1 简单的日 月 年 2 dd mm yy 但周围可能有 之前 之后或关于 字样 任何 其中之一 在这种情况下我们只需要删除这些词即
  • 文本区域最大宽度

    我遇到了文本区域最大宽度的问题 我需要它不超过 table cell two调整大小时的宽度 在此示例中 JSfiddle 示例 http jsfiddle net no1lov3sme t6gzrr7u 1 HTML div class
  • 为什么我需要 Java 中的 MySQL 连接器?

    总是当我想使用使用 MySQL 数据库的程序时 它会强制我安装 MySQL 连接器或mysql 连接器 java jar 为什么我需要 MySQL 连接器以及它是如何工作的 JDBC 是 Java 程序用来访问关系数据库的库 您可以使用它来
  • 在另一个控制器 Ember 中调用控制器方法

    我正在使用 Ember 的 Need Api 来调用另一个控制器中一个控制器的方法 我能够获取控制器的实例 但是当我调用它的方法时 它会返回此错误TypeError Object object Object has no method 我就
  • 在其他 numpy 数组中查找 numpy 数组

    我需要在一个更大的 numpy 数组中找到一个小的 numpy 数组 例如 import numpy as np a np array 1 1 b np array 2 3 3 1 1 1 8 3 1 6 0 1 1 3 4 一个功能 fi
  • 访问 JToken 中的所有项目

    我有一个像这样的 json 块 ADDRESS MAP ADDRESS LOCATION type separator name Address value FieldID 40 LOCATION type locations name L
  • 普罗米修斯动态metrics_path

    Prometheus 允许我从 json 文件动态加载带有 file sd config 的目标 如下所示 prometheus yaml job name kube metrics file sd configs files target
  • 从 MPMoviePlayerController 标准控件中删除/隐藏全屏按钮

    我想要删除 隐藏全屏按钮来自MPMoviePlayerController标准控件 因为全屏模式会产生很多问题 而且也不是我的应用程序的要求 我只想要play stop forward reverse controls 有谁能够帮助我 没有
  • 解析时间戳 - 在 MySQL 还是 PHP 中进行?

    假设你有一张桌子 上面有timestamp列 并且您想将该列解析为两个数组 date and time 您个人是否 a 像这样的查询DATE timestamp TIME timestamp 或者甚至可能尽可能远HOUR timestamp
  • 如何为 JNLP 应用程序设置 Java 系统外观?

    我在 OpenSuse 上运行 Gnome 结果 我的系统外观是 GTK 它有许多丑陋的问题 参见其中一些here http weblogs java net blog campbell archive 2007 02 swing and
  • Angular 2 http get 未获取

    我是 Angular 2 的新手 仍在学习中 我正在尝试使用 get 调用来访问 URL 但即使在浏览器的网络中 get 似乎也没有通过 我找不到正在调用的 get URL 该程序将转到该方法控制台 在 get 调用的上方和下方记录日志 但
  • com.android.volley.NoConnectionError:java.net.UnknownHostException

    我必须使用 Volly 进行一些网络操作 我收到以下代码的 com android volley NoConnectionError java net UnknownHostException String url https www us
  • C# HttpClient PUT

    由于某种原因 我的下面的代码曾经可以工作 现在却引发了一个异常 public static async Task
  • 您可以从 Adob​​e Air 访问 Windows 注册表吗?

    y N 编辑 只读访问权限就可以了 我还没有尝试过 但我想我已经找到了解决方法 Adobe AIR 无法写入 Windows 注册表 但您可以在 AIR 2 中启动本机进程 以下博客文章展示了如何执行此操作 http www adobe c
  • 带换行符的 GWT 标签

    GWT Label 小部件将所有内容解释为文本 而不是 html 标签 这很好 但我希望它能够解释 n as a br 我怎么做 我会创建子类 但我找不到要重写的内容来实现此行为 我可以使用 HTML 小部件 但它会解释所有标签 我需要的只
  • CMake RelWithDebInfo 链接到调试库

    我有一个项目链接到六个库 其中包括 OpenCV 由于发布变体崩溃了 而调试工作正常 只是慢了很多 我想在中编译我的项目RelWithDebInfo配置 然而 DebugOpenCV 库的版本被包含在内 而不是Release OpenCV
  • 改变向量的元素

    假设我有一个包含数千个元素的向量 如果我想让索引在100 200之间的元素变成0 需要什么R代码 另外 我如何计算两个不同值之间的长度 例如 如果我想知道 股价 在 30 40 之间的时间长度 请阅读安装时附带的 R 简介 手册 你的问题之
  • Excel 隐藏/显示功能区上除自定义选项卡之外的所有选项卡

    如何使用 VBA 而不是 XML 隐藏和显示所有标准 Excel 功能区选项卡 我不想隐藏整个功能区 正如这里所要求的 VBA 最小化 Excel 中的功能区 https stackoverflow com questions 190195
  • 添加自定义刻度和标签

    我想在 matplotlib 中添加自定义主要刻度和标签 典型用途是在该位置添加标签math pi与标签 pi 我的目标是让其他刻度保持原样 我想保留原始的主要和次要刻度以及之前选择的格式 但带有这个额外的刻度和标签 我已经找到了一种方法
  • 使用 1:n 中的唯一值创建 n × n 矩阵

    我想在 R 中生成一个随机的 n n 矩阵 离散值范围从 1 到 n 棘手的部分是我希望每个值在行和列中都是唯一的 例如 如果n 3矩阵可能如下所示 1 2 3 2 3 1 3 1 2 或者它可能看起来像这样 2 3 1 1 2 3 3 1