R shiny: Display data set in shiny app - r

I am trying to print dataset values in shiny web app. But I am only able to print data set name using below code. How can I print dataset values?
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")
# ,
# textOutput("txt"),
# 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$x_axis <- renderUI({
col_opts <- get(ds_ext())
selectInput("x_axis2", "Independent Variable:", choices = names(col_opts))
})
}
shinyApp(ui = ui, server = server)
Actually I am trying to solve error in above code "Incorrect number of dimensions". I have written function which would return data frame with only numeric variables so that I can analyze. But getting error in line I guess where I am creating object x_axis. pls help.

Related

R Shiny - calculation using data in csv and user numericInput

I am trying to create a Shiny app where a user can upload a csv file, input a numeric value, add the numeric value to a specific column of data in the csv, then save the raw + calculated data in a table. I generated a simplified Shiny script below using a simple csv file.
When I try and run the app, I get the error:
Problem with mutate() input sum.
[31mx[39m non-numeric argument to binary operator
[34mi[39m Input sum is A + C.
I tried looking up some examples of how to fix this, but was unable to find something that utilized eventReactive() to keep the data table updated with the new calculated data. Any help is greatly appreciated.
library(shiny)
library(dplyr)
ui <- fluidPage(
# Application title
titlePanel("Test"),
# Show a plot of the generated distribution
mainPanel(
fileInput(
inputId = "csvFile",
label = "Upload csv file",
accept = c(".csv")),
uiOutput("C"),
uiOutput("D"),
tableOutput("modifiedData")
)
)
server <- function(input, output) {
output$C <- renderUI(
{numericInput("C", "Variable C", 0)}
)
output$D <- renderUI(
{numericInput("D", "Variable D", 0)}
)
userData <- eventReactive(input$csvFile,
{
req(input$csvFile)
raw_df <- read.csv(input$csvFile$datapath)
calc_df <- raw_df %>%
mutate(sum = A + C)
})
output$modifiedData <- renderTable({userData()})
}
shinyApp(ui = ui, server = server)
You should be using the reactive variable input$C. Also, you should make the eventReactive dependent on input$C. Try this
ui <- fluidPage(
# Application title
titlePanel("Test"),
# Show a plot of the generated distribution
mainPanel(
fileInput(
inputId = "csvFile",
label = "Upload csv file",
accept = c(".csv")),
uiOutput("C"),
uiOutput("D"),
tableOutput("modifiedData")
)
)
server <- function(input, output) {
output$C <- renderUI(
{numericInput("C", "Variable C", 0)}
)
output$D <- renderUI(
{numericInput("D", "Variable D", 0)}
)
userData <- eventReactive(list(input$csvFile, input$C),
{
req(input$csvFile)
raw_df <- read.csv(input$csvFile$datapath)
calc_df <- raw_df %>%
mutate(sum = A + input$C)
})
output$modifiedData <- renderTable({userData()})
}
shinyApp(ui = ui, server = server)

Render multiple plots in shiny ui

I want to make a shiny app where the user is able to select genes. Then he will see all the plots for those genes.
The selection part works fine (I think)
ui <- fluidPage(
titlePanel("Test"),
sidebarPanel(
selectInput("genes", "Genes:", seurat_genes, multiple = TRUE),
),
mainPanel(
uiOutput('out1')
)
)
Now I want to those selected genes to be plotted next to the sidebarPanel:
server <- function(input, output) {
output$out1 = renderUI({
p = FeaturePlot(sc, features=input$genes, cols=c("lightgrey", param$col), combine=FALSE)
names(p) = input$genes
for(i in names(p)) {
p[[i]] = plot.mystyle(p[[i]], title=i)
renderPlot(
print(p[[i]])
)
}
})
}
seurat_genes is data from the analysis with Seurat, which is a library for single-cell RNA-seq data. So the user specifies which genes he wants to look at and FeaturePlotgenerates those plots.
FeaturePlot is a function from Seurat which "Colors single cells on a dimensional reduction plot according to a 'feature' (i.e. gene expression, PC scores, number of genes detected, etc.)"
I'm fairly new to R and especially Shiny, so feel free to suggest any kind of improvements.
Found a solution that works for me:
library(shiny)
library(Seurat)
# This Data is from my Workspace. I have trouble loading it, so its a workaround and is my next Problem.
seurat_genes = sc.markers[["gene"]]
# Define UI for application that draws a histogram
ui <- fluidPage(
titlePanel("Einzeldarstellungen von Genen"),
sidebarPanel(
selectInput("genes", "Gene:", seurat_genes, multiple = TRUE),
),
mainPanel(
splitLayout(cellWidths = c("50%","50%"),uiOutput('out_umap'), uiOutput('out_ridge'))
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$out_umap = renderUI({
out = list()
if (length(input$genes)==0){return(NULL)}
for (i in 1:length(input$genes)){
out[[i]] <- plotOutput(outputId = paste0("plot_umap",i))
}
return(out)
})
observe({
for (i in 1:length(input$genes)){
local({ #because expressions are evaluated at app init
ii <- i
output[[paste0('plot_umap',ii)]] <- renderPlot({
return(FeaturePlot(sc, features=input$genes[[ii]], cols=c("lightgrey", param$col), combine=FALSE))
})
})
}
})
output$out_ridge = renderUI({
out = list()
if (length(input$genes)==0){return(NULL)}
for (i in 1:length(input$genes)){
out[[i]] <- plotOutput(outputId = paste0("plot",i))
}
return(out)
})
observe({
for (i in 1:length(input$genes)){
local({ #because expressions are evaluated at app init
ii <- i
output[[paste0('plot',ii)]] <- renderPlot({
return(RidgePlot(sc, features=input$genes[[ii]], combine=FALSE))
})
})
}
})
}
# Run the application
shinyApp(ui = ui, server = server)

Recomputing renderplot based on renderui user input in RShiny

I'm a bit of an RShiny and R novice. I'm trying to program an RShiny application. It would initially graphs a scatterplot matrix using the first three variables of the dataset by default. The user could then choose their own variable selections from a complete list of variables. Once variables are chosen, the user would click and action button and the graph would be recomputed using the newly selected variables.
I'm using selectinput rather than checkboxinput to accommodate datasets with many variables. I'm using the iris dataset. The code below produces the initial graph and allows the user to select the variables. I just can't figure out how to make it recompute the matrix plot. How do I do this? Thanks!
library(shiny)
runApp(list(
ui = fluidPage(
cols = colnames(iris),
headerPanel('Grow Clusters'),
tabsetPanel(
tabPanel("Plot",
sidebarPanel(
# uiOutput("varselect"),
selectInput("choose_vars", "Select variables to plot",
choices=colnames(iris), selected=iris[1:3], multiple=T),
actionButton("submitButton", "Produce Matrix Plot!")
),
mainPanel(
plotOutput('pairsplot')
)
),
tabPanel("Summary")
,
tabPanel("Table")
)
),
server = function(input, output) {
selectedData <- reactive({
cols = colnames(iris)
selectInput("choose_vars", "Select variables to plot",
choices=cols, selected=cols[1:3], multiple=T)
})
output$pairsplot <- renderPlot({
pairs(iris[1:3], pch = 21)
})
output$varselect <- renderUI({
iris[input$choose_vars]
plotOutput("pairsplot")
})
}
)
)
I think what you are looking for is quo function as in the Chris Beely blog: https://chrisbeeley.net/?p=1116
If you want users to pass arguments and then turn that character vector into objects r can read you need to use quo(input$choose_vars) and then in the plot you need to add !! before that passing variable. Notice you need to load dplyr.
library(shiny)
library(dplyr)
runApp(list(
ui = fluidPage(
cols = colnames(iris),
headerPanel('Grow Clusters'),
tabsetPanel(
tabPanel("Plot",
sidebarPanel(
# uiOutput("varselect"),
selectInput("choose_vars", "Select variables to plot",
choices=colnames(iris), selected=iris[1:3], multiple=T),
actionButton("submitButton", "Produce Matrix Plot!")
),
mainPanel(
plotOutput('pairsplot')
)
),
tabPanel("Summary")
,
tabPanel("Table")
)
),
server = function(input, output) {
selectedData <- reactive({
cols <- colnames(iris)
selectInput("choose_vars", "Select variables to plot",
choices=cols, selected=cols[1:3], multiple=T)
})
output$pairsplot <- renderPlot({
if(is.null(input$choose_vars) || length(input$choose_vars)<2){
pairs(iris[1:3], pch = 21)
} else {
var <- quo(input$choose_vars)
pairs(iris %>% select(!!var), pch = 21)
}
})
output$varselect <- renderUI({
iris[input$choose_vars]
plotOutput("pairsplot")
})
}
)
)

Shiny app with reactive data call from server

I'm trying to make a plot with reactive data from the server. Unfortunately I can't get the plot to work. I'm getting an error like: "Error:EXPR must be a length 1 vector". I tried different styles of plots and different libraries: Quantmod, ggplot, so on. Any suggestions?
Server:
library(shiny)
Dat<-read.csv("A:\\home\\Documents\\Franchise_Failureby_Brand2011.csv", sep=';')
names(Dat)[1]<-paste("Brand")
names(Dat)[2]<-paste("Failure")
names(Dat)[3]<-paste("Disbursement")
names(Dat)[4]<-paste("Disb$X$1000")
names(Dat)[5]<-paste("Chgoff")
Dat1<-Dat[is.na(Dat)==FALSE,]
Dat<-Dat1[1:578,]
# Define server logic required to draw a histogram
shinyServer(function(input, output) {
DatSv <- reactive({
Value <- switch(input$Value,
"Failure"= Dat$Failure[1:10],
"Disbursement"=Dat$Disbursement[1:10],
"Disb$X$1000"=Dat$`Disb$X$1000`[1:10],
"Chgoff"=Dat$Chgoff[1:10])
Brand<-Dat$Brand[1:10]
Brand(input$Value)
})
# Generate plot
output$plot1 <- renderPlot({
library("quantmod")
hist(DatSv(),
main=paste('r', Value, '(', Brand, ')', sep=''))
})
# Generate summary of data
output$summary<-renderPrint({
summary(Dat)
})
})
UI:
library(shiny)
shinyUI(fluidPage(
titlePanel("Plot Franchise Failure"),
sidebarLayout(
sidebarPanel(
radioButtons("n", "Chose output Y Axis:",
c("Failure" ,
"Disbursement",
"Disb$X$1000" ,
"Chgoff" )),
checkboxInput("show_xlab", "Show/Hide X Axis Label", value=TRUE),
checkboxInput("show_ylab", "Show/Hide Y Axis Label", value=TRUE),
checkboxInput("show_title", "Show/Hide Title")
),
mainPanel(
tabsetPanel(
type = "tabs",
tabPanel("Plot", plotOutput("plot1")),
tabPanel("Summary", verbatimTextOutput("summary"))
)
)
)
)
)
Hi the problem comes from connecting the inputs in the UI with the server. In the UI you have given the inputid = "n" for the radioButtons. That means we can get the Value of the Radiobuttons with input$n and not input$Value. The later is always NULL since there is no input with inputid = "Value". I had some other small problems with your code but here is a working version of the server code. I didn't modify the UI
library(shiny)
Dat<-read.csv("A:\\home\\Documents\\Franchise_Failureby_Brand2011.csv", sep=';')
names(Dat)[1]<-paste("Brand")
names(Dat)[2]<-paste("Failure")
names(Dat)[3]<-paste("Disbursement")
names(Dat)[4]<-paste("Disb$X$1000")
names(Dat)[5]<-paste("Chgoff")
Dat1<-Dat[is.na(Dat)==FALSE,]
Dat<-Dat1[1:578,]
# Define server logic required to draw a histogram
shinyServer(function(input, output) {
DatSv <- reactive({
switch(input$n,
"Failure"= gsub("%","",as.character( Dat$Failure)),
"Disbursement"=Dat$Disbursement,
"Disb$X$1000"=gsub("\\$","",as.character( Dat$`Disb$X$1000`)),
"Chgoff"=gsub("%","",as.character(Dat$Chgoff)))
})
# Generate plot
output$plot1 <- renderPlot({
library("quantmod")
hist(as.numeric(DatSv()),
main=paste('Histogram of ',input$n, sep=''),
xlab = input$n)
})
# Generate summary of data
output$summary<-renderPrint({
summary(Dat)
})
})

Cannot coerce class ""histogram"" to a data.frame error in when plotting a graph in Shiny

I have the following data frame that I extract from google analytics
ga_data <- google_analytics_4(viewId = my_id,
date_range = c(Sys.Date()-7, Sys.Date()-1),
metrics = c("sessions","pageviews",
"entrances","bounces"),
dimensions = c("date","deviceCategory",
"channelGrouping"),
anti_sample = TRUE)
Now I want to show a graph of ga_data in a Shiny application. Therefore I include the following code:
library(shiny)
library(ggplot2)
ui <- fluidPage(
titlePanel("Shiny Text"),
sidebarLayout(
sidebarPanel(
selectInput(inputId = "dataset",
label = "Choose a dataset:",
choices = c("ga_data")),
numericInput(inputId = "obs",
label = "Number of observations to view:",
value = 10)
),
mainPanel(
verbatimTextOutput("summary"),
tableOutput("view")
)
)
)
server <- function(input, output) {
ga_data <- google_analytics_4(viewId = 156004565,
date_range = c(Sys.Date()-7, Sys.Date()-1),
metrics = c("sessions","pageviews",
"entrances","bounces"),
dimensions = c("date","deviceCategory",
"channelGrouping"),
anti_sample = TRUE)
datasetInput <- reactive({
switch(input$dataset,
"ga_data" = ga_data)
})
output$view <- renderTable({
hist(ga_data$sessions)
})
}
shinyApp(ui = ui, server = server)
However when I run it I get the following error:
cannot coerce class ""histogram"" to a data.frame
But this is strange cause when I want to make normal plot of the dataframe it does work. So the problem probably has to do with Shiny.
Any thoughts on what can go wrong here?
Since I don't have googleAnalyticsR set up, I reduced your problem to his simple app.
library(shiny)
shinyApp(
fluidPage(tableOutput("table")),
server = function(input, output, session){
output$table <- renderTable({hist(mtcars$mpg)})
}
)
## Warning: Error in as.data.frame.default: cannot coerce class ""histogram"" to a
## data.frame
The problem here is that you try to render a plot using renderTable. If you use renderPlot instead, everything works.
shinyApp(
fluidPage(plotOutput("plot")),
server = function(input, output, session){
output$plot <- renderPlot({hist(mtcars$mpg)})
}
)

Resources