Sanathoi Gurumayum Sanathoi Gurumayum - 22 days ago 6
R Question

Shiny slider input to read rows from csv file

I am new to R and Shiny package. I have a csv file with 4 col and 600 rows and I am trying to plot some graphs using ggplot2. My ui and server codes be like:

dt<-read.csv('file.csv')
server <- function(input, output) {
output$aPlot <- renderPlot({
ggplot(data = dt, aes(x = Col1, y = Col2, group = 'Col3', color = 'Col4')) + geom_point()
})
}


ui <- fluidPage(sidebarLayout(
sidebarPanel(
sliderInput("Obs", "Log FC", min = 1, max = 600, value = 100)
),
mainPanel(plotOutput("aPlot")) ))


Here, I can get the ggplot output but I don't know how to use this slider input to control the numbers of row to be read i.e I want this "Obs" input to define the size of 'Col1' to be used in the graph. Thanks in advance..

Answer Source

Try something like this, example here is with mtcars dataset:

library(shiny)
library(ggplot2)

dt <- mtcars[,1:4]

ui <- fluidPage(
  sidebarPanel(
    sliderInput("Obs", "Log FC", min = 1, max = nrow(dt), value = nrow(dt)-10)
  ),
  mainPanel(plotOutput("aPlot"))
) 

server <- function(input, output) {

  mydata <- reactive({
    dt[1:as.numeric(input$Obs),]
  })

  output$aPlot <- renderPlot({
    test <- mydata()
    ggplot(data = test, aes(x = test[,1], y = test[,2], group = names(test)[3], color = names(test)[4])) +  geom_point()
  })
}

shinyApp(ui = ui, server = server)