I have time series data that I plotted using dygraphs. Now I want to shade some events. The start and end points of these events are stored in a data frame. However, when I try to write a function to add multiple shades, I always get error messages.
I have tried using a for loop directly in the code, but then I get the error message that my dummy variable can't be found. I have tried writing a function with a for loop, but somehow when I apply it, the first argument it uses is ".". Which of course messes up the function.
for (i in 1:length(dataframe$start)){
dyShading(from = dataframe$start[i], to = dataframe$end[i])
}
addshading <- function(periods){
for (i in 1:length(periods[,1])){
x <-dyShading(from = periods$start[i], to = periods$end[i])
}
x
}
Running the for loop directly after dygraph() %>%
gives the following error message:
Error in function_list[k] : object 'i' not found
Running addshading(dataframe)
directly after dygraph() %>%
gives the following error message:
Error in addshading(., dataframe) : unused argument (dataframe)
I hope I made myself clear, I am new to ask for help with coding.
You need to assign dygraph()
to an object first and then incrementally update that object with dyShading()
-
p <- dygraph(your_data)
for (i in 1:nrow(dataframe)) {
p <- p %>% dyShading(from = dataframe$start[i], to = dataframe$end[i])
}
print(p)