Skip to content

Instantly share code, notes, and snippets.

@expersso
Created October 23, 2018 08:51
Show Gist options
  • Save expersso/3cff821fda1af5cc3fb6f382381b6032 to your computer and use it in GitHub Desktop.
Save expersso/3cff821fda1af5cc3fb6f382381b6032 to your computer and use it in GitHub Desktop.
Generate lags with tidyverse
# A rewrite of https://gist.github.com/seanjtaylor/f0f4815427a076c2544fc6a1a80e1dbd
# using some tidyverse tricks to create lagged variables
library(tidyverse)
library(glmnet)
library(broom)
wide_ <- "https://github.com/johnmyleswhite/room_temperatures/raw/master/temperatures.csv" %>%
read_csv() %>%
mutate(room = str_replace(room, "Room ", "r"),
lag = list(0:30)) %>%
unnest(lag) %>%
nest(time, temperature) %>%
mutate(data = map2(data, lag, ~mutate(.x, temperature = lag(temperature, .y)))) %>%
unnest() %>%
unite("var", room, lag, sep = "_l") %>%
spread(var, temperature) %>%
drop_na()
X <- wide_ %>%
select(-ends_with("l0"), -time) %>%
as.matrix()
y <- wide_ %>%
select(ends_with("l0")) %>%
as.matrix()
m <- cv.glmnet(X, y, alpha = 0, family = "mgaussian")
for_plot <- m %>%
coef(s = "lambda.min") %>%
map_dfr(tidy, .id = "room") %>%
filter(row != "(Intercept)") %>%
separate(row, c("to_room", "lag"), sep = '_') %>%
mutate(room = str_remove(room, "_.*"),
lag = as.numeric(str_remove(lag, "l")))
ggplot(for_plot, aes(x = lag, ymax = value)) +
geom_linerange(ymin = 0) +
geom_hline(yintercept = 0, linetype = 'dashed') +
facet_grid(room ~ to_room) +
theme_minimal()
@expersso
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment