Created
April 9, 2018 21:46
-
-
Save Jfortin1/20cb5b2ecd37f6c4bf0d30e6881f55ff to your computer and use it in GitHub Desktop.
Tired of slow split()
This file contains hidden or 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
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