I want to print data set values in R shiny web app. But below code is printing the name of dataset in UI output. How can I print values of dataset?
library(MASS)
library(shinythemes)
library(shiny)
library(ggplot2)
mass.tmp <- data(package = "MASS")[3]
mass.datasets <- as.vector(mass.tmp$results[,3])
ui <- fluidPage(
theme = shinytheme("superhero"),
titlePanel("Linear Regression Modelling"),
sidebarLayout(
sidebarPanel(
selectInput("dsname", "Dataset:",choices = c(mass.datasets))
,
uiOutput("x_axis")
,
tableOutput("tab")
),
mainPanel(
tags$br(),
tags$br()
)
)
)
server <- function(input, output) {
num_ds <- function(ds)
{
nums <- sapply(ds,is.numeric)
num_ds <- ds[,nums]
return(num_ds)
}
ds_ext <- reactive({ num_ds(input$dsname) })
output$tab <- renderTable({ eval(input$dsname) })
# output$x_axis <- renderUI({
# col_opts <- get(ds_ext())
# selectInput("x_axis2", "Independent Variable:", choices = names(col_opts))
# })
}
shinyApp(ui = ui, server = server)
This is full code. I am trying to display data set from MASS package as you see in the code above.
Related
I am using the mtcars dataset and have created another column that is a random number(x) * 2. I have then used the renderDataTable in r shiny to print it. I now want to use renderPlot({}) on the new_col column and any other column. How would I go about calling that new column?
library(shiny)
library(ggplot2)
df<- mtcars
ui<- fluidPage(
titlePanel("Mtcars"),
sidebarLayout(
sidebarPanel(
selectInput(inputID = 'test', label = "TEST", choices = c(1,2,3,4), selected = 3)
mainPanel(
DT::dataTableOutput('table1')
plotOutput('basicplot')
))
server <- function(input, output) {
func<-function(x){
df%>%
mutate(new_col = x*2)
output$table1 <- renderTable({
func(2)
})
output$basicplot <-renderPlot({
plot(* $new_col, *$mpg) #what do i call the new dataframe with the new_col
})
)
shinyApp(ui = ui, server = server)
You had numerous syntax errors. Please check it before posting a question in the future. Try this
library(shiny)
library(ggplot2)
df<- mtcars
ui<- fluidPage(
titlePanel("Mtcars"),
sidebarLayout(
sidebarPanel(
selectInput('test', label = "TEST", choices = names(df)[-1] )
),
mainPanel(
DTOutput('table1'),
plotOutput('basicplot')
)
)
)
server <- function(input, output) {
mydata <- reactive({
df %>%
mutate(new_col = as.numeric(df[[input$test]])*2)
})
output$table1 <- renderDT({
mydata()
})
output$basicplot <-renderPlot({
req(mydata())
df <- data.frame(mydata()$new_col,mydata()$mpg)
plot(df)
})
}
shinyApp(ui = ui, server = server)
I'm trying to pass the node value of a simple network as an argument to a function in Shiny R. However, I'm getting this error:
Error in rsqlite_send_query: no such column: input$id
Can anyone help with this issue? Thanks.
library(shiny)
library(networkD3)
ui <- shinyUI(fluidPage(
fluidRow(
column(4, simpleNetworkOutput("simple")),
column(4, DT::dataTableOutput("table"))
)
))
server <- shinyServer(function(input, output, session) {
session$onSessionEnded(stopApp)
output$simple <- renderSimpleNetwork({
sn<-simpleNetwork(df)
sn$x$options$clickAction = 'Shiny.onInputChange("id",d.name)'
sn
})
output$table <- DT::renderDataTable(DT::datatable(get(funct(input$id))))
})
shinyApp(ui = ui, server = server)
take out the deparse and substitute from your sprintf command, and add single quotes around the value you want to match in the SQL statement you're generating
get rid of the get function because you're not trying to "get" an object
for example....
library(shiny)
library(networkD3)
library(DT)
library(sqldf)
df <- read.csv(header = T, text = '
source,name,age,hair
dad,Jon X,18,brown
dad,Jon Y,22,blonde
')
funct <-
function (n) {
isp <- sprintf("Select df.age From df Where df.name='%s';", n)
isd <- sqldf::sqldf(isp)
return(isd)
}
ui <- shinyUI(fluidPage(
fluidRow(
column(4, simpleNetworkOutput("simple")),
column(4, DT::dataTableOutput("table"))
)
))
server <- shinyServer(function(input, output, session) {
session$onSessionEnded(stopApp)
output$simple <- renderSimpleNetwork({
sn<-simpleNetwork(df)
sn$x$options$clickAction = 'Shiny.onInputChange("id",d.name)'
sn
})
output$table <- DT::renderDataTable(DT::datatable(funct(input$id)))
})
shinyApp(ui = ui, server = server)
however, if all you want is to display a value associated with a given selection, I highly suggest drastically reducing the complexity to something like this
library(shiny)
library(networkD3)
df <- read.csv(header = T, text = '
source,name,age,hair
dad,Jon X,18,brown
dad,Jon Y,22,blonde
')
ui <- shinyUI(fluidPage(
fluidRow(
column(4, simpleNetworkOutput("simple")),
column(4, textOutput("text"))
)
))
server <- shinyServer(function(input, output, session) {
session$onSessionEnded(stopApp)
output$simple <- renderSimpleNetwork({
sn <- simpleNetwork(df)
sn$x$options$clickAction <- 'Shiny.onInputChange("id", d.name)'
sn
})
output$text <- renderPrint({ df$age[df$name == input$id] })
})
shinyApp(ui = ui, server = server)
i've been trying to interactively zoom in certain parts of a chartSeries with zoomChart and shiny, but can't find the right solution. I would use dateRangeInput or a slider, but i'm not sure how to connect the zoomChart-option from quantmod with shiny. As you might have already assumed, I'm relatively new to shiny and very thankful for your advices!
edit: Data is in the xts-format.
MyCode:
library(quantmod)
library(shiny)
date_range <- as.POSIXct(index(data))
if (interactive()) {
options(device.ask.default = FALSE)
ui <- fluidPage(
titlePanel("Select Range to zoom-in:"),
sidebarLayout(
sidebarPanel(
dateRangeInput("Range", "Choose Date Range:", min=first(date_range),
max=last(date_range), format = "dd-mm-yyyy")
),
mainPanel(
plotOutput("Plot")
)
)
)
server <- function(input, output) {
output$Plot <- renderPlot({
chartSeries(data, type = c("auto", "candlesticks", "matchsticks", "bars","line"),
theme=chartTheme("white"), name=paste(start(data), end(data),sep = " "))
zoomChart(dateRangeInput)
})
}
shinyApp(ui, server)
}
Actually, you were very close. Note the changes in dateRangeInput(): The start and end argument are used instead of min, max. And then you can use the input on the server-side to use zoom-chart.
library(quantmod)
library(shiny)
getSymbols("YHOO")
data <- YHOO
date_range <- index(data)
if (interactive()) {
options(device.ask.default = FALSE)
ui <- fluidPage(
titlePanel("Select Range to zoom-in:"),
sidebarLayout(
sidebarPanel(
dateRangeInput("Range", "Choose Date Range:", start=first(date_range),
end=last(date_range), format = "yyyy-mm-dd")
),
mainPanel(
plotOutput("Plot")
)
)
)
server <- function(input, output) {
output$Plot <- renderPlot({
chartSeries(data, type = c("auto", "candlesticks", "matchsticks", "bars","line"),
theme=chartTheme("white"), name=paste(start(data), end(data),sep = " "))
zoomChart(paste(input$Range, collapse = "::"))
})
observe({
print(input$Range)
})
}
shinyApp(ui, server)
}
As #drmariod indicated It would be beneficial to have a fully reproducible exmaple, which was easy to get in this case via getSymbols().
I am having difficulty implementing this code on a more complicated setup that I have. My goal is to let the user change column values with the projected values rendered from numericInput button. Global.R is not an option as there are many operations placed on the dataset before the final version is reached. I have everything setup other than being able to observe the input$action and change the dataframe when an action occurs.
ui.R
shinyUI(
fluidPage(
titlePanel("Basic DataTable"),
# Create a new row for the table.
fluidRow(
selectInput("select", label = h3("Select box"),
choices = unique(data$Projection),
selected = unique(data$Projection)[1]),
numericInput("num", label = h3("Numeric input"), value = unique(data$Projection)[1]),
submitButton(text = "Apply Changes", icon = NULL),
dataTableOutput(outputId="table")
)
)
)
server.R
library(shiny)
# Load the ggplot2 package which provides
# the 'mpg' dataset.
# Given that you are not plotting this line is
### useless library(ggplot2)
# Define a server for the Shiny app
shinyServer(function(input, output) {
# Filter data based on selections
output$table <- renderDataTable({
data$User_Prediction[data$Projection==input$select] <<- input$num
data
})
})
global.r
data <- as.data.frame(c(98,99,34))
names(data) <- "Projection"
data$User_Prediction <- 0
Data is stored in server.R as such
data <-reactive({
...
...
...
data
})
I am trying to bring in data which is stored in the reactive function into
d <- reactiveValues(dat=data)
I have tried
d <- data()
d <- data
d <- reactiveValues(dat=data)
Is there any way I could access the data, because otherwise your code works.
If you want to do this without observeEvent you could do this:
data <- as.data.frame(c(98,99,34))
names(data) <- "Projection"
data$User_Prediction <- 0
ui <- shinyUI(
fluidPage(
titlePanel("Basic DataTable"),
# Create a new row for the table.
fluidRow(
column(12,
selectInput("select", label = h3("Select box"),
choices = unique(data$Projection),
selected = unique(data$Projection)[1]),
numericInput("num", label = h3("Numeric input"), value = unique(data$Projection)[1]),
actionButton('btn',"Apply Changes"),
dataTableOutput(outputId="table")
)
)
)
)
server <- shinyServer(function(input, output) {
d <- reactive({
data
})
dat <- reactiveValues(dat=NULL)
observe({
dat$dat <- d()
})
observe({
input$btn
isolate({
num <- input$num
sel <- input$select
})
dat$dat$User_Prediction[dat$dat$Projection==sel] <- num
#d2 <- dat
})
# Better way
# observeEvent(input$btn,{
# dat$dat$User_Prediction[dat$dat$Projection==sel] <- num
# })
# Filter data based on selections
output$table <- renderDataTable({
dat$dat
})
})
shinyApp(ui=ui,server=server)
I am using R shiny to develop a interactive analysis tool. Now I want to do classification tree based on variables check in checkboxGroupInput. How can I select that subset of data? THX!
UI:
dateInput("date","Enter date:",value = date),
checkboxGroupInput("variable", "Variable:",
choices = names ,selected = names
)
server I tried, but doesn't work:
dataall <- reactive({
filename <- paste0("dataall_'", input$date, "'.RData")
load(filename)
feature.test[,names(feature.test) %in% input$variable]
})
feature.test is data in loaded file.
Hard to understand what you want since you don't subset the file you load. What is feature.test ?
Here is a simple example to how to subset a data frame using an input and shiny reactivity :
shiny::runApp(list(
ui = basicPage(
selectInput("specy", "Specy", choices = levels(iris$Species)),
tableOutput("content")
),
server = function(input, output, session) {
output$content <- renderTable({
iris[iris$Species == input$specy, ]
})
}
))
EDIT ## :
Subset by column :
shiny::runApp(list(
ui = pageWithSidebar(
headerPanel("Example"),
sidebarPanel(
checkboxGroupInput("variable", "Variable:", choices = names(iris))
),
mainPanel(
tableOutput("content")
)
),
server = function(input, output, session) {
output$content <- renderTable({
if(is.null(input$variable))
return()
iris[input$variable]
})
}
))
"variable" is supposed to be "date" since this is the control that you are referencing in the UI part, as in:
checkboxGroupInput( "date", "Variable:",
choices = names ,selected = names
)
For data.table you need to add a ,with=FALSE or use a temporary variable in the server code:
# Load libraries
library(shiny)
library(data.table)
# Copy dataset
irisDT=copy(iris)
setDT(irisDT)
# Shiny app
shiny::runApp(list(
# UI
ui = pageWithSidebar(
headerPanel("Example"),
sidebarPanel(
checkboxGroupInput("variable", "Variable:", choices = names(iris))
),
mainPanel(
tableOutput("content")
)
),
# Server
server = function(input, output, session) {
output$content <- renderTable({
if(is.null(input$variable))
return()
# iris[input$variable] # data.frame
irisDT[, input$variable, with=FALSE] # data.table
# Alternatively:
# tmp <- input$variable
# irisDT[, ..tmp]
})
}
))