Skip to content

Instantly share code, notes, and snippets.

@arcaravaggi
Created June 19, 2018 14:24
Show Gist options
  • Save arcaravaggi/8e03ccd634de026a184bbb042f37fc71 to your computer and use it in GitHub Desktop.
Save arcaravaggi/8e03ccd634de026a184bbb042f37fc71 to your computer and use it in GitHub Desktop.
Copy row duplicating data Xi times
# 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