Skip to content

Instantly share code, notes, and snippets.

@mrdwab
Created October 18, 2014 10:52
Show Gist options
  • Select an option

  • Save mrdwab/98175d209b642ee39ae9 to your computer and use it in GitHub Desktop.

Select an option

Save mrdwab/98175d209b642ee39ae9 to your computer and use it in GitHub Desktop.
library(splitstackshape)
library(reshape2)
library(dplyr)
library(tidyr)
dfx <- data.frame(Var1=c("A", "B", "C", "D", "B", "C", "D", "C", "D", "D"),
Var2=c("E", "E", "E", "E", "A", "A", "A", "B", "B", "C"),
Var1out = c(1,-1,-1,-1,1,-1,-1,1,-1,-1),
Var2out= c(-1,1,1,1,-1,1,1,-1,1,1))
dfx <- do.call(rbind, replicate(10000, dfx, FALSE))
fun1 <- function() {
dfx <- copy(dfx)
dfx %>%
setnames(gsub("(Var)([0-9])(out)", "\\3\\2", names(dfx))) %>%
mutate(id = sequence(nrow(dfx))) %>%
merged.stack(var.stubs = c("Var", "out"), sep = "var.stubs") %>%
dcast.data.table(id ~ Var, value.var = "out", fill = 0)
}
fun2 <- function() {
cols <- unique(unlist(dfx[1:2]))
M <- matrix(0, nrow = nrow(dfx), ncol = length(cols), dimnames = list(NULL, cols))
M[cbind(sequence(nrow(dfx)), match(dfx$Var1, cols))] <- dfx$Var1out
M[cbind(sequence(nrow(dfx)), match(dfx$Var2, cols))] <- dfx$Var2out
M
}
fun3 <- function() {
dfy <- data.frame(Var = unlist(dfx[, 1:2]),
VarOut = unlist(dfx[, 3:4]),
indx = 1:nrow(dfx))
acast(dfy, indx ~ Var, value.var = "VarOut", fill = 0)
}
fun4 <- function() {
dfy <- data.frame(Var = unlist(dfx[, 1:2]),
VarOut = unlist(dfx[, 3:4]),
indx = 1:nrow(dfx))
spread(dfy, Var, VarOut , fill = 0)[, -1]
}
system.time(fun1())
# user system elapsed
# 0.3 0.0 0.3
system.time(fun2())
# user system elapsed
# 0.30 0.00 0.29
system.time(fun3())
# user system elapsed
# 1.53 0.07 1.39
system.time(fun4())
# user system elapsed
# 1.53 0.01 1.30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment