Eva Balgova
Eva Balgova

Reputation: 77

Rearranging data rows

I have a data frame with 2 variables (columns) and 108 rows and I need to rearrange the order of the rows for both columns as following: 1, 2, 3, 55, 56, 57, 4, 5, 6, 58, 59, 60, 7, 8, 9, 61, 62, 63, 10, 11, 12, 64, 65, 66, 13, 14, 15, 67, 68, 69, 16, 17, 18, 70, 71, 72, 19, 20, 21, 73, 74, 75, 22, 23, 24, 76, 77, 78, 25, 26, 27, 79, 80, 81, 28, 29, 30, 82, 83, 84, 31, 32, 33, 85, 86, 87, 34, 35, 36, 88, 89, 90, 37, 38, 39, 91, 92, 93, 40, 41, 42, 94, 95, 96, 43, 44, 45, 97, 98, 99, 46, 47, 48, 100, 101, 102, 49, 50, 51, 103, 104, 105, 52, 53, 54, 106, 107, 108...for this I am trying to use the dplyr arrange function with no success though. Could anyone help to troubleshoot this?

Many thanks.

Upvotes: 1

Views: 58

Answers (1)

akrun
akrun

Reputation: 886928

We can do this programmatically. Create the sequence of rows vector ('v1'), then convert it to a matrix with 2 columns ('m1'), split the data.frame converted matrix with a grouping variable created with gl so that we split at every 3 columns to create a list of data.frames, loop over the list with lapply, transpose (t), and convert the matrix to vector (c), unlist the list elements and use that as index for subsetting. The transpose is done so that when we do the concatenate (c), it can make use of the default behavior i.e. columnwise order in getting the values as a vector.

v1 <- seq_len(nrow(df1))
m1 <- matrix(v1, nrow = 2, byrow = TRUE)
ind <- unlist(lapply(split.default(as.data.frame(m1), 
         as.integer(gl(ncol(m1), 3, ncol(m1)))), function(x) c(t(x)))) 
df1[ind,]

Or with dplyr, we do the same approach, by creating row_number column, then grouped by a column created with gl, we arrange the rows

library(dplyr)
df1 %>%
   transmute(v1 = row_number())  %>%
   group_by(grp = as.integer(gl(n(), n()/2, n()))) %>%
   group_by(grp1 = gl(n(), 3, n())) %>% 
   ungroup %>%
   arrange(grp1) %>% 
   pull(v1) %>% 
   arrange(df1, .)

Upvotes: 1

Related Questions