In this example, I have 3 variables, 2 variable domains and 2 years. I want to be able to build a shiny app where I choose combinations of 2 or 3 variables and domains to draw a chart.
Depending on the variables and domain selected, a series resulting from the mean is drawn (variable m).
library(tidyverse)
theme_set(theme_minimal())
df <- tibble(d = c(1,1,2,2),
year = c(2015, 2016, 2015, 2016),
v1 = c(3,5,4,10),
v2 = c(7,11,13,18),
v3 = c(1,2,3,4))
draw_chart <- function(df, listv, d){
df2 <- df %>%
gather("variable", "value", 3:5)
df3 <- df2 %>%
filter(variable %in% listv)
df4 <- df3 %>%
group_by(d, year) %>%
summarise(value = mean(value)) %>%
mutate(variable = "m")
df5 <- bind_rows(df3, df4)
df5 <- df5 %>%
mutate(year = as.character(year)) %>%
mutate(year = as.Date(year, "%Y"))
df5 <- df5 %>%
mutate(year = lubridate::year(year))
df5 <- df5 %>%
filter(d == 1)
# format(df5$year, "%Y")
# Visualization
ggplot(df5, aes(x = year, y = value)) +
geom_line(aes(color = variable, linetype = variable)) +
scale_color_discrete() +
scale_x_continuous(breaks = c(2015,2016))
}
listv <- c("v1", "v2") # this list can change
# these are several possibilities of chosing variables
# listv <- c("v2", "v3")
# listv <- c("v1", "v3")
# listv <- c("v1", "v2", "v3")
# and d can also be chosed to be 1 or 2
draw_chart(df, listv, 2)