# Little useless-useful R functions – Return matrix elements in spiral order

[This article was first published on

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

**R – TomazTsql**, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Another one from the Leetcode challenge. This time, get the elements (single values) from the matrix in a spiral order with a starting position of [1,1].

So, the basic idea is to retrieve a vector of elements from a matrix in the following order:

In this order, we get the vector with the following elements:

So, we need to create the boundaries, count the rows | columns and return a vector of elements. Here is the useless function:

## return elements from matrix in spiral order matrix_spiral <- function(mat) { mr <- dim(mat)[1] nc <- dim(mat)[2] total_len <- mr*nc #path #TRUE -> visited; FALSE -> unvisited visit <- matrix(FALSE, nrow=mr, ncol=nc) #helper variables gor <- 1 dol <- mr levo <- 1 desno <- nc res <- vector() while (length(res) < total_len) { for (i in levo:nc) { if (!visit[gor, i]) { res <- c(res, mat[gor,i]) visit[gor, i] <- TRUE } } gor <- gor + 1 for (i in gor:mr) { if (!visit[i, desno]) { res <- c(res, mat[i,desno]) visit[i, desno] <- TRUE } } desno <- desno - 1 if (gor <= dol) { for (i in desno:levo) { if (!visit[dol, i]) { res <- c(res, mat[dol,i]) visit[dol, i] <- TRUE } } dol <- dol - 1 } if (levo <= desno) { for (i in dol:gor) { if (!visit[i, levo]) { res <- c(res, mat[i,levo]) visit[i, levo] <- TRUE } } levo <- levo + 1 } } return(res) }

As always, the complete code is available on Github in Useless_R_function repository. The sample file in this repository is here (filename: *Spiral_matrix.R*). Check the repository for future updates.

Happy R-coding and stay healthy!

To

**leave a comment**for the author, please follow the link and comment on their blog:**R – TomazTsql**.R-bloggers.com offers

**daily e-mail updates**about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.