How can I create multiple shades in dygraphs using a data frame? - r

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)

Related

Creating a function to save different columns from a list into a dataframe

I am trying to look into a dataset using a forloop. The data contains lists and I'm trying to create a function which saves the output of the loop into a dataframe. It is something similar to this example
test = function(inputname) {
if(is_empty(obs$company$inputname[[1]])){
data[[i]] = obs
} else {
data[[i]] = obs$company %>%
unnest(inputname)
}
df_inputname = data %>%
rbindlist(fill = TRUE) %>%
select(company:date)
}
test(address)
Im trying to get this to return a dataframe called 'df_address' containing information from the input_name = address from the list in the data. But i get an error messasage saying that the column doesnt exists. The idea is I can look up different variables within the list and save the results as a dataframe. Ideally I would want to be able to search for multiple variables and add them into a dataframe, but in this first go Im simply annoyed as why I ge tthe error. Any ideas?

Using a for loop to create dynamic objects in R

I'm trying to use a for loop to create a set of dynamic objects in R. These will contain a list of organisations and values against a certain metric--each output will be the values of an individual metric.
In practice, this will be used to create chart objects using ggplot2, which I'll then use in RMarkdown. For the example below, it's just a sample using a head() function for each metric.
I tried using the paste function to create this name, but it gives the following error:
Error in paste("organisation_short", "_", MetricIDs[x]) <-
head(organisationdata_Jan2021) : target of assignment expands to
non-language object
I understand that the assign function might help, but I'm not sure how to use it. (My attempts also produced errors). I found a similar question in the link below, but it's set up in a way that pipes data directly into assign. I'm also not clear what "value = ." is doing. This query is below:
dynamically name objects in R
I believe the "value = ." refers to the data being piped into the assign function. I created an alternative version which is in the code below.
Error in assign(x = organisationdata_Jan2021, value = paste0("sampledata", :
invalid first argument
The idea is to create output files along the lines of: organisation_short_ABC123, organisation_short_ABC323, organisation_short_KJM088
I would be grateful for any guidance you might have!
MetricIDs <- c('ABC123','ABC323','KJM088')
# Attempt using paste
for (x in 1:3)
{
organisationdata_Jan2021 <- organisationdata_CM0040_Jan2021 %>% filter(Metric_ID==MetricIDs[x]) # Filter data to specific Metric ID
paste("organisation_short","_", MetricIDs[x]) <- head(organisationdata_Jan2021) # Goal: Create object that includes the Metric ID.
}
# Attempt using assign
for (x in 1:3)
{
organisationdata_Jan2021 <- organisationdata_CM0040_Jan2021 %>% filter(Metric_ID==MetricIDs[x]) # Filter data to specific Metric ID
assign(x=organisationdata_Jan2021, value=paste0("sampledata",MetricIDs[x]))
}
# Expected object names: organisation_short_ABC123, organisation_short_ABC323, organisation_short_KJM088
# This will be used to create chart objects using ggplot2, and those objects will be used in an R MarkDown document.

R error in data frame : Unexpected end of document when adding new column

I made data frame containing date this way:
DD<-seq(as.Date("2019/01/01"), by = "day", length.out =31)
DD2 <- data.frame("Date"=DD, var = c(1:31))
DD2<-DD2
Now I tried to add a 3rd column but compiler starts raising error msg when I tried to add by mutate a 3rd column into it:
DD2<-DD2%>% //Unexpected end of document
mutate(Date2=Date%%5)
Above code ie reproducible. Why is this error raising ?
What I get when I run your code I get: "Error in Ops.Date(Date, 5) : %% not defined for "Date" objects", but maybe you're using a library that is OK with the notation (I am just using dplyr). If you simply run:
DD2<-DD2 %>% mutate(Date2=Date-5)
it successfully adds the third, mutated column, so the problem is in the %% operation itself.

How to `dput` a `ggplot` object?

I am looking for a way to save some ggplot objects for later use. The dput function creates a string that when passed to dget() would return the errors of unexpected <:
The first one is here: .internal.selfref = <. This can be easily solved by setting .internal.selfref to NULL.
The remaining seven are distributed across different attributes, with the arguments being <environment>. I tried to change the <environment>'s to something like NULL or environment(), but none of them works - the environment is not set right and the object not found error is returned.
Some searches led me to the function ggedit::dput.ggedit. But it gives me the error:
# Error in sprintf("%s = %s", item, y) :
# invalid type of argument[2]: 'symbol'
I am thinking, either I set the environments right in using the dput function, or I figure out why ggedit::dput.ggedit does not work...
Any idea?
Not using dput(), but to save your ggplot objects for later use, you could save them as .rds files (just like any R objects).
Example:
my_plot <- ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy))
saveRDS(my_plot, "my_plot.rds")
And to restore your object in another session, another script, etc.
my_plot <- readRDS("my_plot.rds")
You can try a tidyverse
Save the plot beside the data in a tibble using nest and map.
library(tidyverse)
res <- mtcars %>%
as.tibble() %>%
nest() %>%
mutate(res=map(data, ~ggplot(.,aes(mpg, disp)) + geom_point()))
Then save the data.frame using save or saveRDS.
Finally, call the plot:
res$res
The size is 4kb for tibble(mtcars) vs. 21kb with plot.

Saving a group of histograms in R as a data.frame

I am trying to save a histogram for every file in a list. I cannot load more than 1 file at a time due to their large size. Normally I would use a symbolic object name for each file's histogram and iterate the name for each item in the list. I am having trouble figuring out how to do this in R so instead I attempt to save each hist as a column of a data.frame. The code is as follows:
filelist <- list.files("dir/")
file.hist <- data.frame(check.rows = FALSE)
for(i in 1:length(filelist) {
file <- read.csv(capture.output(cat("dir/", filelist[i], sep = "")))
file.hist[[i]] <- hist(file$Value, breaks = 200)
}
The error message that results is:
Error in `[[<-.data.frame`(`*tmp*`, i, value = list(breaks = c(0, 200, :
replacement has 6 rows, data has 0
I have googled the error message and it seems like it might be related to how you go about initializing the data from although I have to admit that my brain is fried this close to Thanksgiving. Has anyone out there dealt with an solved a similar problem? I am not married to this approach.

Resources