Search code examples
rdplyrggvis

R ggvis interactive slider for calculating y values (e.g. for background correction)


I would like to use a ggvis slider to visually do a background correction of my data:

library("dplyr")
library("ggvis")
library("lubridate")
data <- data.frame(timestamp = Sys.time() - hours(10:1),
                   signal = rnorm(10),
                   temperature = rnorm(10))

mySlider <- input_slider(0, 2, value = 1, step = 0.1, label = "T-correction")
data %>% 
  ggvis(~timestamp, ~signal) %>%
  layer_paths() %>%
  layer_paths(x = ~timestamp, y = ~temperature, stroke := "red") %>%
  mutate(new_signal = signal - mySlider * temperature) %>%  # here, I would like to add in the slider
  layer_paths(x = ~timestamp, y = ~new_signal, stroke := "darkgreen")

I get an Error in function () : non-numeric argument to binary operator. Is ggvis capable of doing this or what did I do wrong?


Solution

  • You can do this with the map argument of input_slider. But it appears that you have to explicitly call data$signal and data$temperature.

    # specify slider
    mySlider <- input_slider(0, 2, value = 1, step = 0.1, label = "T-correction", 
                             map = function(x)  data$signal - x * data$temperature)
    # plotting
    data %>% 
      ggvis(~timestamp, ~signal) %>%
      layer_paths() %>%
      layer_paths(x = ~timestamp, y = ~temperature, stroke := "red") %>%
      layer_paths(x = ~timestamp, y = mySlider, stroke = "darkgreen")