Last active
August 9, 2021 17:29
-
-
Save jmbarbone/ff2151fdf036b722b9d434366f8fbdb3 to your computer and use it in GitHub Desktop.
playing around with recycling in R
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
recycle <- function(x, y, each = FALSE) { | |
vals <- list(x, y) | |
n <- lengths(vals) | |
if (n[1] == n[2]) { | |
return(vals) | |
} | |
if (n[1] == 0 | n[2] == 0) { | |
return(vals) | |
} | |
if (n[1] == 1) { | |
if (each) { | |
vals[[1]] <- rep(vals[[1]], each = n[2]) | |
} else { | |
vals[[1]] <- rep(vals[[1]], times = n[2]) | |
} | |
return(vals) | |
} | |
if (n[2] == 1) { | |
if (each) { | |
vals[[2]] <- rep(vals[[2]], each = n[2]) | |
} else { | |
vals[[2]] <- rep(vals[[2]], times = n[2]) | |
} | |
return(vals) | |
} | |
if (n[1] < n[2]) { | |
op <- 1 | |
min <- n[1] | |
max <- n[2] | |
} else { | |
op <- 2 | |
min <- n[2] | |
max <- n[1] | |
} | |
if (max %% min != 0) { | |
stop("cannot recycle x and y") | |
} | |
if (each) { | |
vals[[op]] <- rep(vals[[op]], each = max %/% min) | |
} else { | |
vals[[op]] <- rep(vals[[op]], times = max %/% min) | |
} | |
vals | |
} | |
recycle(1:3, NULL) | |
recycle(c("this", "that"), 1:4) | |
recycle(c("this", "that"), 1:4, each = TRUE) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment