0
votes

I use the following function to perform a weighted t-test on a data set.

 pvfct <- function(var, weights) {
     req(input$groupb)
     req(input$sex)
     req(input$age)
     req(input$education)
     if(is.null(input$groupa) == FALSE & is.null(input$groupb) == FALSE & is.null(input$sex) == FALSE & is.null(input$age) == FALSE & is.null(input$education) == FALSE) {

         data <- df()
         data1 <- data %>%
             select(var, group1, weightrake) %>%
             filter(group1 == 1)

         data2 <- data %>%
             select(var, group1, weightrake) %>%
             filter(group1 == 2)

         result <- wtd.t.test(data1[[var]], data2[[var]], data1[[weights]], data2[[weights]], samedata = FALSE)
         result <- as.numeric(result$coefficients[3])
         result <- round(result, 2)
         result
     }
     else {}
 }

result <- pvfct("Image_Vertrauen_ALLBRANDS_top2", "weightrake")

The function works perfectly fine as long as I define it inside Server.R. But what I want is to define all my functions in the global scope. I guess it has to do something to do with the inputs, since these are reactive?! Can anyone help me?

Why is this technically not working?

1
What do you mean by global scope? You want to define it in your shiny application outside the server? - Vishesh Shrivastav

1 Answers

0
votes

It is necessary to define all reactive expressions as part of server part of the code. Global scope can only contain static elements like library calls, data manipulation which once performed remain as is even if input changes. Global scope does not reexecute every time the widget input changes, it is only the server code which changes.

Since, your data filtering is dependent on an input condition, it will have to go inside server to work.

To understand how reactivity in shiny works, I find following articles pretty helpful

As part of your code, everytime the function is run, value of input$groupa is looked up [if its false or not], this value lookup is something which global is unable to do and can only be performed by server.