How to turn an entire dataframe into a reactive object on start? - r

My shiny app relies on a main CSV dataframe from which users pick whatever variable they want to feed charts, maps, etc. I now want users to be able to create new variables by combining existing variables.
Problem: I need the new variables to be stored in that main CSV dataframe along all the other variables, and make them available just for the session, for every other control/map/chart. Of course I can't just append the new variable to my CSV dataframe because it's not a reactive object.
So I'm naturally thinking of turning the CSV dataframe into a reactive object on start.
I tried
reactivedf<- reactiveVal()
reactivedf(df)
But for some reason this approach doesn't work, in the sense that when the app starts, all the charts and maps are empty.
However, the reactive object does "wakes up" with a eventReactive statement that updates the reactivedf, and the maps and charts come to life:
reactivedf <- eventReactive(input$button, {
<code to create a new variable and append it to reactivedf>
}
How can I make the reactivedf fully available on start?

Always a good idea to read the docs at least once.
reactivedf <- reactiveValues()
reactivedf$df <- df
It's good to give credit where credit is due. You didn't "naturally think" anything, you were put on this by a comment to your previous similar question.

Related

Upload a .xlsx file to Shiny and load in all the tabs as a list [duplicate]

I have a shiny app and when I run it I get an error saying that an object of type ‘closure’ is not subsettable. What is that and how can I fix it?
Note: I wrote this question as this comes up a lot, and the possible dupes are either not shiny related or so specific that it is not obvious that the answers are broadly applicable.
See also this question which covers this error in a non-Shiny context.
How to fix this:
This is a very common error in shiny apps. This most typically appears when you create an object such as a list, data.frame or vector using the reactive() function – that is, your object reacts to some kind of input. If you do this, when you refer to your object afterwards, you must include parentheses.
For example, let’s say you make a reactive data.frame like so:
MyDF<-reactive({ code that makes a data.frame with a column called “X” })
If you then wish to refer to the data.frame and you call it MyDF or MyDF$X you will get the error. Instead it should be MyDF() or MyDF()$X You need to use this naming convention with any object you create using reactive().
Why this happens:
When you make a reactive object, such as a data.frame, using reactive() it is tempting to think of it as just like any other non-reactive data.frame and write your code accordingly. However, what you have created is not really a data.frame. Rather, what you have made is instructions, in the form of a function, which tell shiny how to make the data.frame when it is needed. When you wish to actually use this function to get the data.frame you have to use the parenthesis, just like you would any other function in R. If you forget to use the parenthesis, R thinks you are trying to use part of a function and gives you the error. Try typing:
plot$x
at the command line and you will get the same error.
You may not see this error right when your app starts. Reactive objects have what is called “lazy” evaluation. They are not evaluated until they are needed for some output. So if your data.frame is only used to make a plot, the data.frame will not exist until the user sees the plot for the first time. If when the app starts up the user is required to click a button or change tabs to see the plot, the code for the data.frame will not be evaluated until that happens. Once that happens, then and only then will shiny use the current values of the inputs to run the function that constructs the data.frame needed to make the plot. If you have forgotten to use the parentheses, this is when shiny will give you the error. Note that if the inputs change, but the user is not looking at the plot, the function that makes the data.frame will not be re-run until the user looks at the plot again.

Rstudio - how to write smaller code

I'm brand new to programming and an picking up Rstudio as a stats tool.
I have a dataset which includes multiple questionnaires divided by weeks, and I'm trying to organize the data into meaningful chunks.
Right now this is what my code looks like:
w1a=table(qwest1,talm1)
w2a=table(qwest2,talm2)
w3a=table(quest3,talm3)
Where quest and talm are the names of the variable and the number denotes the week.
Is there a way to compress all those lines into one line of code so that I could make w1a,w2a,w3a... each their own object with the corresponding questionnaire added in?
Thank you for your help, I'm very new to coding and I don't know the etiquette or all the vocabulary.
This might do what you wanted (but not what you asked for):
tbl_list <- mapply(table, list(qwest1, qwest2, quest3),
list(talm1, talm2, talm3) )
names(tbl_list) <- c('w1a', 'w2a','w3a')
You are committing a fairly typical new-R-user error in creating multiple similarly named and structured objects but not putting them in a list. This is my effort at pushing you in that direction. Could also have been done via:
qwest_lst <- list(qwest1, qwest2, quest3)
talm_lst <- list(talm1, talm2, talm3)
tbl_lst <- mapply(table, qwest_lst, talm_lst)
names(tbl_list) <- paste0('w', 1:3, 'a')
There are other ways to programmatically access objects with character vectors using get or wget.

Create an arbitrary number of plots with inputs in shiny using modules

Thank you very much for your time and help!
My goal: create an arbitrary number of plots (ggplot2) in shiny where each comes with a number of controls (y axis min/max, plot download button, plot, hover info for the plot). Important: implement it using shiny modules, where a module is created to build a single ui element and another module calls the single element module and loops to create an arbitrary number of ui elements (I can get it to work without using modules).
It works for me if the data for the plots (and the vector which is used to loop over to create each plot) are loaded globally in the app. This global data gist demonstrates my use case using iris dataset loaded globally. Here how it looks like when it works: snapshot of the app
However, my problem is that I can't figure out how to write a shiny module when the data are not loaded globally. Real life example: I pull the data from a database, do some processing on the server side and then I want to generate the plots. Reproducible example using the iris dataset loaded on the server side: server data gist
The error I get when the data are loaded on the server side (when running server data gist):
Error in as.vector: cannot coerce type 'environment' to vector of type 'character'
I believe this is something to do with how I write the module for the multiple ui elements (I suspect multiplePlotsUI).
My question: What will be the correct way to write the module that calls another module and loops over a vector to generate an arbitrary number of ui elements (y axis controls, plot download button, plot with hover info) when the data are not loaded globally?
I don't know if it'll help, but as far as I can see, your input.data() function is not defined in you multiplePlots call (local.data <- input.data())
You're also calling
dm <- dat()
twice, but this dat() function doesn't seem to be defined

Reactive data just once and then stock it globally in R Shiny

So I'm trying to develop with R Shiny, I ask the user to do 5 file inputs. And then I have a reactive function mergeFun() which will cast and merge the data in one data set once the inputs are done.
Then I have multiple buttons, boxplots, renderUI, outputs, PCA, regression trees,... in my different tabPanels and each one of these calls the function mergeFun() in order to do the statistic analysis.
So as it is making quite some time after the inputs to load everyone of these panels at once, I was wondering if there was a way to just call the function globally and stock the merged data in one global variable.
I was thinking maybe because I call this function x times once in each analysis in the tabPanels, it was causing the time lapse.
So I would just be able to call the data instead of calling the function mergeFun()
I'm posting the code modified, to give you an idea about what I am doing
mergeFun <- reactive({
#So there I had my test about if my files existed
#I delete for visibility
cast <- dcast(input,var1 + var2,value.var = "var3")
mergeAll <- merge(input2,cast,by=c("var1","var2","var3"))
data.frame(mergeAll)
})
So this is my mergeFun() and then I have many reactive and renderUI which will all start like this :
output$xcol <- renderUI({
df <-mergeFun()
if (is.null(df)) return(NULL)
...
...
...
})
So maybe calling mergeFun() x times isn't programatically efficient?

Importing and accessing large data files in Shiny

I have an app where I want to pull out values from a lookup table based on user inputs. The reference table is a statistical test, based on a calculation that'd be too slow to do for all the different combinations of user inputs. Hence, a lookup table for all the possibilities.
But... right now the table is about 60 MB (as .Rdata) or 214 MB (as .csv), and it'll get much larger if I expand the possible user inputs. I've already reduced the number of significant figures in the data (to 3) and removed the row/column names.
Obviously, I can preload the lookup table outside the reactive server function, but it'll still take a decent chunk of time to load in that data. Does anyone have any tips on dealing with large amounts of data in Shiny? Thanks!
flaneuse, we are still working with a smaller set that you but we have been experimenting with:
Use rds for our data
As #jazzurro mentioned rds above, and you seem to know how to do this, but the syntax for others is below.
Format .rds allows you to bring in a single R object so you can rename it if needs be.
In your prep data code, for example:
mystorefile <- file.path("/my/path","data.rds")
# ... do data stuff
# Save down (assuming mydata holds your data frame or table)
saveRDS(mydata, file = mystorefile)
In your shiny code:
# Load in my data
x <- readRDS(mystorefile)
Remember to copy your data .rds file into your app directory when you deploy. We use a data directory /myapp/data and then file.path for store file is changed to "./data" in our shiny code.
global.R
We have placed our readRDS calls to load in our data in this global file (instead of in server.R before shinyServer() call), so that is run once, and is available for all sessions, with the added bonus it can be seen by ui.R.
See this scoping explanation for R Shiny.
Slice and dice upfront
The standard daily reports use the most recent data. So I make a small latest.dt in my global.R of a smaller subset of my data. So the landing page with the latest charts work with this smaller data set to get faster charts.
The custom data tab which uses the full.dt then is on a separate tab. It is slower but at that stage the user is more patient, and is thinking of what dates and other parameters to choose.
This subset idea may help you.
Would be interested in what others (with more demanding data sets have tried)!

Resources