Created
June 19, 2018 14:24
-
-
Save arcaravaggi/8e03ccd634de026a184bbb042f37fc71 to your computer and use it in GitHub Desktop.
Copy row duplicating data Xi times
This file contains 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
# Copy all rows in a dataframe according to their maximum value. | |
# Copy all other integers an appropriate number of times, filling the last cell with 0. | |
# | |
# By StackOverflow user, CPak: https://stackoverflow.com/a/50930471/9962100 | |
# | |
# Example | |
# df <- data.frame(A1 = c(0,2,0,3), A2 = c(1,0,2,0), A3 = c(0,1,3,2)) | |
# ans <- data.frame(A1 = c(0,2,2,0,0,0,3,3,3), A2 = c(1,0,0,2,2,0,0,0,0), A3 = c(0,1,0,3,3,3,2,2,0)) | |
# library(magrittr) | |
# test <- do.call(rbind, lapply(seq_len(nrow(df)), function(x) explodeR(df[x, ]))) %>% as.data.frame | |
# all.equal(test, ans) | |
explodeR <- function(row) { | |
M <- max(row) | |
apply(row, 2, function(x) c(rep(x, times=x), rep(0, times=M-x))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment