I am struggeling with a VERY simple problem :
I would like to run 2 indices combinations in a loop : i=1,j=1, i=1,j=2,i=1,j=3..... then switch to i=1,j=2 i=2,j=2 i=3,j=2... and so on until i=n,j=n
I wrote the following code which sadly doesn't work properly :
a <- function(n) {
for (i in 1:n) {
for (j in 1:n) {
print(i,j)
}
}
}
#I expect to get 1,1 1,2 1,3 1,4... 2,1 2,2... but this is not the result.
Thank you in advance,
Your code does work! Just printing with comma only prints the first.
Instead try separating by comma in a string:
a <- function(n) {
for (i in 1:n) {
for (j in 1:n) {
print(paste(i, j, sep=', '))
}
}
}
Ex:
> 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"
>
Your code only prints the numbers on the left.