r - How to reverse a double loop? -


i have double loop prints objects list grid based upon given number of rows , columns. issue want provide users "byrow" option can decide fill across columns or rows first. way i've gotten work far doubling code , changing loop order seems incredibly inefficient. simplified version of code below.

please let me know if more information required. or guidance appreciated.

plot ( x = 1:4 , y = 1:4 , type = "n")  w <- list ( "a" , "b" , "c" , "d" ,"e" , "f")  nrow <- 3  ncol <- 2  if (length(w) > nrow * ncol ) warning("not enough rows/columns")   ( in 1:nrow) (j in 1:ncol){     if( !length(w) ) break     text(i,j , w[[1]])     w <- w[-1] } 

edit:

apologies should have highlighted more clearly. above code highly simplified version of actual code. main list list of lists , function using instead of text not vectorised matrix won't work specific case.

looking through provided answers though have managed use rev , expand.grid functions others have used create following:

plot ( x = 1:4 , y = 1:4 , type = "n")  w <- list ( "a" , "b" , "c" , "d" ,"e" )  nrow <- 3  ncol <- 2 byrow <- t  if (length(w) > nrow * ncol ) warning("not enough rows/columns")  grid <- expand.grid(1:nrow , 1:ncol)  if ( !byrow) grid <- rev(grid) grid <- grid[1:length(w),]  mapply( text , grid[,1] ,grid[,2] , w) 

am still interested see if there better way of doing though still.

text() vectorized - , plays matrices (which have byrow argument already). no loop needed. change byrow true @ top if want switch up.

byrow = false  plot ( x = 1:4 , y = 1:4 , type = "n") w <- list ( "a" , "b" , "c" , "d" ,"e" , "f") ## why list, not vector??  nrow <- 3  ncol <- 2 if (length(w) > nrow * ncol ) warning("not enough rows/columns")  # no loop needed mat = matrix(unlist(w), nrow = nrow, ncol = ncol, byrow = byrow) text(x = expand.grid(1:nrow, 1:ncol), labels = mat) 

matrix has it's own warning if rows , column numbers aren't don't work out - if can recycle evenly silently fill in, warning may preferable.


Comments