Shiny beginner query

Hi friends,

Started with shiny and tutorial by Joe Chang below example

I am unable to get the reason why paste function is used in the lm function.

selected <- reactive({
iris[, c(input$xcol, input$ycol)]
})

model <- reactive({
lm(paste(input$ycol, "~", input$xcol), selected())
})


If i write the code as below it also works is it inefficient.

x<- reactive(iris[,input$xcol])
y<- reactive(iris[,input$ycol])
selected <-reactive(bind_cols(x(),y()))

model <- reactive({
lm((y()~ x()), selected())

Hi @jdurvesh,

The first argument to the lm() should be a syntactically valid formula which describes the model to be fit. In the original code, paste() is used to paste together the y-variable and x-variable (along with ~) to create a valid formula (e.g., y ~ x or Sepal.Length ~ Sepal.Width). Paste is just creating this formula from the selected inputs input$ycol and input$xcol.

I didn't run your code, but if you say it works, so be it. But it certainly jumps through more hoops than necessary to get to the same result.

These three lines of your code pull the data apart, only to bind it back together again:

x<- reactive(iris[,input$xcol])
y<- reactive(iris[,input$ycol])
selected <-reactive(bind_cols(x(),y()))

Meanwhile this code from the original code only subsets those variables from the data set in one step:

selected <- reactive({
    iris[, c(input$xcol, input$ycol)]
  })
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.