如何 运行 r 中的两个索引

How to run two indices in r

我正在为一个非常简单的问题而苦苦挣扎:

我想 运行 循环中的 2 个索引组合:i=1,j=1,i=1,j=2,i=1,j=3..... 然后切换到 i=1,j=2 i=2,j=2 i=3,j=2... 直到 i=n,j=n

我写了下面的代码,遗憾的是不能正常工作:

a <- function(n) {
  for (i in 1:n)  {
    for (j in 1:n) {
     print(i,j)
    }
  }
}

#我期望得到 1,1 1,2 1,3 1,4... 2,1 2,2... 但结果不是这样

提前谢谢你,

您的代码确实有效!仅使用逗号打印只会打印第一个。

改为尝试在字符串中用逗号分隔:

a <- function(n) {
  for (i in 1:n)  {
    for (j in 1:n) {
     print(paste(i, j, sep=', '))
    }
  }
}

例如:

> a(3)
[1] "1, 1"
[1] "1, 2"
[1] "1, 3"
[1] "2, 1"
[1] "2, 2"
[1] "2, 3"
[1] "3, 1"
[1] "3, 2"
[1] "3, 3"
> 

您的代码只打印左边的数字。

另一种编写函数的方法是在 lseq 个长度为 l.

的列表上使用 expand.grid
f <- \(l) do.call(paste,
                  cbind(expand.grid(replicate(l - 1, seq.int(l), simplify=FALSE)), 
                        sep=', '))
f(3)
# [1] "1, 1" "2, 1" "3, 1" "1, 2" "2, 2" "3, 2" "1, 3" "2, 3" "3, 3"

f(4)
#  [1] "1, 1, 1" "2, 1, 1" "3, 1, 1" "4, 1, 1" "1, 2, 1" "2, 2, 1" "3, 2, 1"
#  [8] "4, 2, 1" "1, 3, 1" "2, 3, 1" "3, 3, 1" "4, 3, 1" "1, 4, 1" "2, 4, 1"
# [15] "3, 4, 1" "4, 4, 1" "1, 1, 2" "2, 1, 2" "3, 1, 2" "4, 1, 2" "1, 2, 2"
# [22] "2, 2, 2" "3, 2, 2" "4, 2, 2" "1, 3, 2" "2, 3, 2" "3, 3, 2" "4, 3, 2"
# [29] "1, 4, 2" "2, 4, 2" "3, 4, 2" "4, 4, 2" "1, 1, 3" "2, 1, 3" "3, 1, 3"
# [36] "4, 1, 3" "1, 2, 3" "2, 2, 3" "3, 2, 3" "4, 2, 3" "1, 3, 3" "2, 3, 3"
# [43] "3, 3, 3" "4, 3, 3" "1, 4, 3" "2, 4, 3" "3, 4, 3" "4, 4, 3" "1, 1, 4"
# [50] "2, 1, 4" "3, 1, 4" "4, 1, 4" "1, 2, 4" "2, 2, 4" "3, 2, 4" "4, 2, 4"
# [57] "1, 3, 4" "2, 3, 4" "3, 3, 4" "4, 3, 4" "1, 4, 4" "2, 4, 4" "3, 4, 4"
# [64] "4, 4, 4"

注: "R version 4.1.2 (2021-11-01)".