Skip to content

Instantly share code, notes, and snippets.

@Jfortin1
Created April 9, 2018 21:46
Show Gist options
  • Save Jfortin1/20cb5b2ecd37f6c4bf0d30e6881f55ff to your computer and use it in GitHub Desktop.
Save Jfortin1/20cb5b2ecd37f6c4bf0d30e6881f55ff to your computer and use it in GitHub Desktop.
Tired of slow split()
splitByRow <- function(Y, f){
require(tidyverse)
names <- dimnames(Y)
Y <- as.matrix(Y); dimnames(Y) <- names
#levels <- sort(unique(f)) %>% as.character
temp <- split(Y, f=f)
names <- names(temp)
ns <- table(f)[names]
temp <- lapply(1:length(temp), function(i){
x <- matrix(temp[[i]], ncol=ncol(Y), nrow=ns[[i]], byrow=FALSE)
colnames(x) <- colnames(Y)
x
})
names(temp) <- names
temp
}
splitByCol <- function(Y, f){
require(tidyverse)
names <- dimnames(Y)
Y <- as.matrix(Y); dimnames(Y) <- names
#levels <- sort(unique(f)) %>% as.character
temp <- split(t(Y), f=f)
names <- names(temp)
ns <- table(f)[names]
temp <- lapply(1:length(temp), function(i){
x <- matrix(temp[[i]], nrow=nrow(Y), ncol=ns[[i]], byrow=TRUE)
rownames(x) <- rownames(Y)
x
})
names(temp) <- names
temp
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment