Created
December 4, 2020 01:00
-
-
Save mrdwab/7271ff36c3ebd08e2b5dec774b0d51d1 to your computer and use it in GitHub Desktop.
Wraps rows into new rows, optionally including the source row. https://stackoverflow.com/q/65118797/1270695
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
row_wrap <- function(input, ...) { | |
UseMethod("row_wrap") | |
} | |
row_wrap.data.frame <- function(input, ncols, row_ind = FALSE) { | |
if (ncol(input) %% ncols != 0) stop("Number of columns not divisible by desired output") | |
data.frame(row_wrap.matrix(input, ncols, row_ind)) | |
} | |
row_wrap.matrix <- function(input, ncols, row_ind = FALSE) { | |
if (ncol(input) %% ncols != 0) stop("Number of columns not divisible by desired output") | |
out <- matrix(t(input), ncol = ncols, byrow = TRUE, | |
dimnames = list(NULL, colnames(input)[sequence(ncols)])) | |
if (isTRUE(row_ind)) { | |
cbind(row_ind = rep(1:nrow(input), each = ncol(input)/ncols), out) | |
} else { | |
out | |
} | |
} | |
# sample data | |
set.seed(1) | |
M <- m <- matrix(sample(c(-5:5, NA), 24, TRUE), nrow = 2) | |
colnames(m) <- paste0("V", sequence(ncol(m))) | |
df <- data.frame(m) | |
df | |
## V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 | |
## 1 3 1 -4 5 5 -5 -1 0 1 -1 3 -1 | |
## 2 -2 -5 1 -4 -3 -1 4 4 3 -1 3 -1 | |
row_wrap(M, 2) | |
## [,1] [,2] | |
## [1,] 3 1 | |
## [2,] -4 5 | |
## [3,] 5 -5 | |
## [4,] -1 0 | |
## [5,] 1 -1 | |
## [6,] 3 -1 | |
## [7,] -2 -5 | |
## [8,] 1 -4 | |
## [9,] -3 -1 | |
## [10,] 4 4 | |
## [11,] 3 -1 | |
## [12,] 3 -1 | |
row_wrap(m, 3, TRUE) | |
## row_ind V1 V2 V3 | |
## [1,] 1 3 1 -4 | |
## [2,] 1 5 5 -5 | |
## [3,] 1 -1 0 1 | |
## [4,] 1 -1 3 -1 | |
## [5,] 2 -2 -5 1 | |
## [6,] 2 -4 -3 -1 | |
## [7,] 2 4 4 3 | |
## [8,] 2 -1 3 -1 | |
row_wrap(df, 6) | |
## V1 V2 V3 V4 V5 V6 | |
## 1 3 1 -4 5 5 -5 | |
## 2 -1 0 1 -1 3 -1 | |
## 3 -2 -5 1 -4 -3 -1 | |
## 4 4 4 3 -1 3 -1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment