Skip to content

Instantly share code, notes, and snippets.

@jmbarbone
Last active August 9, 2021 17:29
Show Gist options
  • Save jmbarbone/ff2151fdf036b722b9d434366f8fbdb3 to your computer and use it in GitHub Desktop.
Save jmbarbone/ff2151fdf036b722b9d434366f8fbdb3 to your computer and use it in GitHub Desktop.
playing around with recycling in R
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