0

Has anyone come across and managed to solve an issue with sampling from normal distribution in Shiny R, please? I'm struggling to find a solution: this question was asked before but no answer was found.

Sampling using rnorm results in output consisting entirely of NAs in Shiny; no such problems outside Shiny app.

library(shiny)

ui<-shinyUI(fluidPage(

sidebarPanel(
sliderInput("Rmax", label="growth", min=0,max=2, value=1),
sliderInput("sd_Rmax", label = "sd for rmax", min=0.05, max=1, value = 0.35),
sliderInput("K", label="K", min=2, max=70, value = 10.1),
sliderInput("sd_K", label="sd for K", min=2,max=70, value=1.48),
sliderInput("ss", label="Sample Size", min=30,max=300, value=30)
),

mainPanel(
verbatimTextOutput("Statistics"))
))

server<-shinyServer(function(input, output){
data<-reactive({

#here are my inputs; convert inputs to log-scale:
ln_rmax<-log(input$Rmax, base=exp(1))
ln_K<-log(input$K, base=exp(1))
ln_sd_rmax<-log(input$sd_Rmax, base=exp(1))
ln_sd_K<-log(input$sd_K, base=exp(1))

#sample from normal
s_ln_rmax<-rnorm(input$ss*19,mean=ln_rmax,sd=ln_sd_rmax) # Here's where the problem is
s_ln_K<-rnorm(input$ss*19,mean=ln_K,sd=ln_sd_K)

phi<-seq(0,0.9, by=0.05)
phi_s<-rep(phi, input$ss)

#convert back
s_rmax<-exp(s_ln_rmax)
s_K<-exp(s_ln_K)
D<-runif(19*input$ss,min=0.2*s_K, max=0.8*s_K)

#combine into a dataframe
combs<-as.data.frame(cbind(s_rmax,s_K, phi_s, D))
})

output$Statistics <- renderPrint({ summary(data())})
})

shinyApp(server = server, ui = ui)

This is the warning message I get: Warning in rnorm(input$ss * 19, mean = ln_rmax, sd = ln_sd_rmax) : NAs produced. Strangely, the problem is with the first sampled variable s_rmax, and not the second sampled variable s_K.

I need to use the first variable further along in my code.

Thank you for any help in advance.

user2196886
  • 1
  • 1
  • 1

1 Answers1

1

Your default sd parameter for rnorm is negative (-1.049822) for s_ln_rmax. However, it is positive for s_ln_K (0.3920421), hence why you can extract a random sample for one set of parameters and not the other.

In fact, you will have to change all your paramters in the sliderInput for "sd_Rmax".

sliderInput("sd_Rmax", label = "sd for rmax", min=0.05, max=1, value = 0.35)

precludes any possibility of getting a random distribution because of how you transform input$sd_Rmax. It must be something of this sort if you want to keep transforming the input using a natural log:

sliderInput("sd_Rmax", label = "sd for rmax", min=1, max=Inf, value = 2.5)
Chrisss
  • 3,211
  • 1
  • 16
  • 13
  • Thank you - it makes sense now. Sadly, your workaround will not work for my purposes; I'll truncate my inputs instead of using logs. Sigh. Thank you again. – user2196886 Sep 27 '16 at 19:37