Correlation coefficient for a Scatter plot - r

I have plotted scatterplot for each country, and I am trying to add a correlation coefficient under the scatterplot, but I keep getting errors saying "Selections can't have missing values." even after using na.rm
Can someone help me with this??
I appreciate any help you can provide.
data link EuropeIndia
#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com/
#
library(shiny)
library(plotly)
library(DT)
library(tidyverse)
library(car)
library(ggpubr)
covid <- read.csv("EuropeIndia.csv")
title <- tags$a(href='https://ourworldindata.org/covid-vaccinations?country=OWID_WRL',
'COVID 19 Vaccinations')
# Define UI for application
ui <- fluidPage(
headerPanel(title = title),
# Application title
titlePanel("COVID vaccinations: Deaths Vs All variables"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
selectInput("location", "1. Select a country",
choices = covid$location, selectize = TRUE, multiple = FALSE),
br(),
helpText("2. Select variables for scatterplot"),
selectInput(inputId = "y", label = "Y-axis:",
choices = c("total_deaths", "new_deaths"),
selected = "Deaths",),
br(),
selectInput(inputId = "x", label = "X-axis:",
choices = names(subset(covid,select = -c(total_deaths,new_deaths,
iso_code, continent,date,location), na.rm =TRUE)),
selectize = TRUE,
selected = "Comparator variables")
),
mainPanel(
textOutput("location"),
#plotOutput("Scatterplot"),
tabsetPanel(
type = "tabs",
tabPanel("Scatterplot", plotlyOutput("scatterplot"),
verbatimTextOutput("correlation"),
verbatimTextOutput("interpretation")),
tabPanel("Summary of COVID data", verbatimTextOutput("summary")),
tabPanel("Dataset", DTOutput("dataset")))
)
)
)
# Define server logic
server <- function(input, output) {
output$location <- renderPrint({locationfilter <- subset(covid, covid$location == input$location)})
output$summary <- renderPrint({summary(covid)})
output$dataset <- renderDT(
covid, options = list(
pageLength = 50,
initComplete = JS('function(setting, json) { alert("done"); }')
)
)
output$scatterplot <- renderPlotly({
ggplotly(
ggplot(subset(covid, covid$location == input$location),
aes(y = .data[[input$y]], x = .data[[input$x]],col = factor(stringency_index)))+
geom_smooth()+geom_point()+labs(col ="Stringency Index")
)
})
output$correlation <- renderText({
x= subset(covid, covid$location == input$location) %>% dplyr::select(as.numeric(!!!input$x, na.rm =TRUE))
y= subset(covid, covid$location == input$location) %>% dplyr::select(as.numeric(!!!input$y, na.rm = TRUE))
var(x,y, na.rm = T, use)
cor(x,y, method = 'pearson', na.rm =T)
})
}
# Run the application
shinyApp(ui = ui, server = server)

First of all you should select just one Country from the selection list.
For error checking I propose you the next code.
library(shiny)
library(plotly)
library(DT)
library(tidyverse)
library(car)
library(ggpubr)
covid <- read.csv("EuropeIndia.csv")
title <- tags$a(href='https://ourworldindata.org/covid-vaccinations?country=OWID_WRL',
'COVID 19 Vaccinations')
# Define UI for application
ui <- fluidPage(
headerPanel(title = title),
# Application title
titlePanel("COVID vaccinations: Deaths Vs All variables"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
selectInput("location", "1. Select a country",
choices = covid$location[1], selectize = TRUE, multiple = FALSE),
br(),
helpText("2. Select variables for scatterplot"),
selectInput(inputId = "y", label = "Y-axis:",
choices = c("total_deaths", "new_deaths"),
selected = "Deaths",),
br(),
selectInput(inputId = "x", label = "X-axis:",
choices = names(subset(covid,select = -c(total_deaths,new_deaths,
iso_code, continent,date,location), na.rm =TRUE)),
selectize = TRUE,
selected = "Comparator variables")
),
mainPanel(
textOutput("location"),
#plotOutput("Scatterplot"),
tabsetPanel(
type = "tabs",
tabPanel("Scatterplot", plotlyOutput("scatterplot"),
verbatimTextOutput("correlation"),
verbatimTextOutput("interpretation")),
tabPanel("Summary of COVID data", verbatimTextOutput("summary")),
tabPanel("Dataset", DTOutput("dataset")))
)
)
)
# Define server logic
server <- function(input, output) {
output$location <- renderPrint({locationfilter <- subset(covid, covid$location == input$location)})
output$summary <- renderPrint({summary(covid)})
output$dataset <- renderDT(
covid, options = list(
pageLength = 50,
initComplete = JS('function(setting, json) { alert("done"); }')
)
)
output$scatterplot <- renderPlotly({
ggplotly(
ggplot(subset(covid, covid$location == input$location),
aes(y = .data[[input$y]], x = .data[[input$x]],col = factor(stringency_index)))+
geom_smooth()+geom_point()+labs(col ="Stringency Index")
)
})
output$correlation <- renderText({
x <- covid[covid$location == input$location, input$x]
y <- covid[covid$location == input$location, input$y]
xy = data.frame(x,y)
xy = xy[complete.cases(xy),]
var(xy)
cor(xy,method = 'pearson')
})
}
# Run the application
shinyApp(ui = ui, server = server)

Related

How to create a summary table (means) of the inputs from a shiny app?

I have a Shiny app that collects Heights and Weights using the interface from the shiny app.
What I would like to have, is a table just below the raw value table that gives me an average of the heights and weights that were inputed into the app, and changes as rows are entered or deleted.
I tried to add some code to the replaceData function but that throws an error.
library(shiny)
library(tidyverse)
library(DT)
df <- dplyr::tibble(Height = numeric(), Weight = numeric())
ui <- fluidPage(
# App title ----
titlePanel("DT + Proxy + Replace Data"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Slider for the number of bins ----
shiny::textInput(inputId = "height", label = "height"),
shiny::textInput(inputId = "weight", label = "weight"),
shiny::actionButton(inputId = "add", label = "Add"),
shiny::selectInput(inputId = "remove_row", label = "Remove Row",
choices = 1:nrow(df)),
shiny::actionButton(inputId = "remove", label = "Remove")
),
# Main panel for displaying outputs ----
mainPanel(
# Output: Histogram ----
DT::DTOutput(outputId = "table"),
DT::DTOutput(outputId = "mean_table"),
)
)
)
# Define server logic required to draw a histogram ----
server <- function(input, output, session) {
mod_df <- shiny::reactiveValues(x = df)
output$table <- DT::renderDT({
mod_df$x
})
#table 2
output$mean_table <- DT::renderDT({
mod_df$x
})
shiny::observe({
shiny::updateSelectInput(session, inputId = "remove_row",
choices = 1:nrow(mod_df$x))
})
shiny::observeEvent(input$add, {
mod_df$x <- mod_df$x %>%
dplyr::bind_rows(
dplyr::tibble(Height = as.numeric(input$height),
Weight = as.numeric(input$weight)))
})
shiny::observeEvent(input$remove, {
mod_df$x <- mod_df$x[-as.integer(input$remove_row), ]
})
proxy <- DT::dataTableProxy('table')
shiny::observe({
DT::replaceData(proxy, mod_df$x)
})
}
shinyApp(ui, server)
We can create a reactive with the means of Height and Weight. This will ensure that changes from mod_df$x will be reflected when computing the means.
mean_table_df <- eventReactive(mod_df$x, {
mod_df$x %>%
summarise(across(c("Height", "Weight"), ~ mean(., na.rm = TRUE)))
})
# table 2
output$mean_table <- DT::renderDT({
datatable(mean_table_df())
})
Complete app:
library(shiny)
library(tidyverse)
library(DT)
df <- dplyr::tibble(Height = numeric(), Weight = numeric())
ui <- fluidPage(
# App title ----
titlePanel("DT + Proxy + Replace Data"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: Slider for the number of bins ----
shiny::textInput(inputId = "height", label = "height"),
shiny::textInput(inputId = "weight", label = "weight"),
shiny::actionButton(inputId = "add", label = "Add"),
shiny::selectInput(
inputId = "remove_row", label = "Remove Row",
choices = 1:nrow(df)
),
shiny::actionButton(inputId = "remove", label = "Remove")
),
# Main panel for displaying outputs ----
mainPanel(
# Output: Histogram ----
DT::DTOutput(outputId = "table"),
DT::DTOutput(outputId = "mean_table"),
)
)
)
# Define server logic required to draw a histogram ----
server <- function(input, output, session) {
mod_df <- shiny::reactiveValues(x = df)
output$table <- DT::renderDT({
mod_df$x
})
shiny::observe({
shiny::updateSelectInput(session,
inputId = "remove_row",
choices = 1:nrow(mod_df$x)
)
})
shiny::observeEvent(input$add, {
mod_df$x <- mod_df$x %>%
dplyr::bind_rows(
dplyr::tibble(
Height = as.numeric(input$height),
Weight = as.numeric(input$weight)
)
)
})
shiny::observeEvent(input$remove, {
mod_df$x <- mod_df$x[-as.integer(input$remove_row), ]
})
proxy <- DT::dataTableProxy("table")
shiny::observe({
DT::replaceData(proxy, mod_df$x)
})
# TABLE 2
mean_table_df <- eventReactive(mod_df$x, {
mod_df$x %>%
summarise(across(c("Height", "Weight"), ~ mean(., na.rm = TRUE)))
})
# table 2
output$mean_table <- DT::renderDT({
datatable(mean_table_df())
})
}
shinyApp(ui, server)

Loading bar from Waiter package doesn't disappear after its use [SHINY]

I am creating a Shiny app and I have started using the Waiter package.
When I load the app, before doing anything, we cannot see anything (at it is expected). When I generate the plot, the loading bar appears but when it finishes, it doesn't disappear. It stays a white box that it still can be seen.
Loading....
It has finished.
Does anyone know how to remove it?
Thanks in advance!
Code:
library(shiny)
library(magrittr)
library(DT)
library(ggplot2)
library(waiter)
new_choices <- setNames(names(mtcars), names(mtcars))
ui <- fluidPage(
# Application title
titlePanel("My shiny app"),
sidebarLayout(
sidebarPanel(
tabsetPanel(
tabPanel("Selection",
selectInput("x_axis", "Choose x axis",
choices = new_choices),
selectInput("y_axis", "Choose y axis",
choices = new_choices),
hr(),
),
tabPanel("Titles",
hr(),
textInput(inputId = "title", "You can write the title:", value = "This is the title"),
textInput(inputId = "xlab", "You can re-name the x-axis:", value = "x-axis...."),
textInput(inputId = "ylab", "You can re-name the y-axis:", value = "y-axis ...."),
),
tabPanel("Calculations",
hr(),
checkboxInput("log2", "Do the log2 transformation", value = F),
checkboxInput("sqrt", "Calculate the square root", value = F),
)
),
useWaitress(),
actionButton(inputId = "drawplot", label = "Show the plot")
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("plot"),
)
)
)
server <- function(input, output, session) {
waitress <- Waitress$new(theme = "overlay-percent", min = 0, max = 10)
data <- reactive({
mtcars
})
filtered_data <- reactive({
data <- data()
if(input$log2 == TRUE){
data <- log2(data+1)
}
if(input$sqrt == TRUE){
data <- sqrt(data)
}
return(data)
})
v <- reactiveValues()
observeEvent(input$drawplot, {
# use notification
waitress$notify()
for(i in 1:10){
waitress$inc(1) # increase by 10%
Sys.sleep(.3)
}
v$plot <- ggplot() +
geom_point(data = filtered_data(),
aes_string(x = input$x_axis, y = input$y_axis)) +
xlab(input$xlab) +
ylab(input$ylab) +
ggtitle(input$title)
waitress$close() # hide when done
})
output$plot <- renderPlot({
if (is.null(v$plot)) return()
v$plot
})
}
shinyApp(ui, server)
Feels like a bug to me. You may file an issue to the waiter github repository and ask them to fix it. Meanwhile, a workaround we can do is to manually show and hide the bar by ourselves.
library(shiny)
library(magrittr)
library(DT)
library(ggplot2)
library(waiter)
library(shinyjs)
new_choices <- setNames(names(mtcars), names(mtcars))
ui <- fluidPage(
# Application title
titlePanel("My shiny app"),
sidebarLayout(
sidebarPanel(
tabsetPanel(
tabPanel("Selection",
selectInput("x_axis", "Choose x axis",
choices = new_choices),
selectInput("y_axis", "Choose y axis",
choices = new_choices),
hr(),
),
tabPanel("Titles",
hr(),
textInput(inputId = "title", "You can write the title:", value = "This is the title"),
textInput(inputId = "xlab", "You can re-name the x-axis:", value = "x-axis...."),
textInput(inputId = "ylab", "You can re-name the y-axis:", value = "y-axis ...."),
),
tabPanel("Calculations",
hr(),
checkboxInput("log2", "Do the log2 transformation", value = F),
checkboxInput("sqrt", "Calculate the square root", value = F),
)
),
useWaitress(),
useShinyjs(),
actionButton(inputId = "drawplot", label = "Show the plot")
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("plot")
)
)
)
server <- function(input, output, session) {
waitress <- Waitress$new(theme = "overlay-percent", min = 0, max = 10)
data <- reactive({
mtcars
})
filtered_data <- reactive({
data <- data()
if(input$log2 == TRUE){
data <- log2(data+1)
}
if(input$sqrt == TRUE){
data <- sqrt(data)
}
return(data)
})
v <- reactiveValues()
observeEvent(input$drawplot, {
# use notification
show(selector = '.waitress-notification.notifications')
waitress$notify()
for(i in 1:10){
waitress$inc(1) # increase by 10%
Sys.sleep(.3)
}
v$plot <- ggplot() +
geom_point(data = filtered_data(),
aes_string(x = input$x_axis, y = input$y_axis)) +
xlab(input$xlab) +
ylab(input$ylab) +
ggtitle(input$title)
waitress$close()
hide(selector = '.waitress-notification.notifications')
})
output$plot <- renderPlot({
if (is.null(v$plot)) return()
v$plot
})
}
shinyApp(ui, server)

Shiny Application for Linear Regression with dynamic variable dropdown based on user upload

As the title describes, I'm simply trying to create a shiny application that allows the user to generate linear regression plots based on an imported csv file. After importing the file the dropdown for the variables of interest should be dynamically updated.
As the code below shows, I'm able to accomplish that with mtcars but I'm not able to do the same with an imported files that would have different dependent and independent variables .
Thank you for your help
data(mtcars)
cols <- sort(unique(names(mtcars)[names(mtcars) != 'mpg']))
ui <- fluidPage(
titlePanel("Build a Linear Model for MPG"),
sidebarPanel(
#fluidRow(
#column(4,
#tags$h3('Build a Linear Model for MPG'),
fileInput(
inputId = "filedata",
label = "Upload data. csv",
accept = c(".csv")
),
fileInput(
inputId = "filedata1",
label = "Upload data. csv",
accept = c(".csv")
),
selectInput('vars',
'Select dependent variables',
choices = cols,
selected = cols[1:2],
multiple = TRUE)
#)
), #sidebarpanel
mainPanel( column(4, verbatimTextOutput('lmSummary')),
column(4, plotOutput('diagnosticPlot')))
) #fluidpage
server <- function(input, output) {
data <- reactive({
req(input$filedata)
read.csv(input$filedata$datapath) %>% rename_all(tolower) %>%
filter(driver_name == input$driver_name & county == input$county & model == input$model)
})
lmModel <- reactive({lm(sprintf('mpg ~ %s', paste(input$vars, collapse = '+')),
data = mtcars)})
# lmModel <- reactive({lm(sprintf('mpg ~ %s', paste(input$vars, collapse = '+')),
# data = mtcars)})
output$lmSummary <- renderPrint({
summary(lmModel())
})
output$diagnosticPlot <- renderPlot({
par(mfrow = c(2,2))
plot(lmModel())
})
}
shinyApp(ui = ui, server = server)```
To dynamically select x and y axis variables, you can try the following
ui <- fluidPage(
titlePanel("Build a Linear Model"),
sidebarPanel(
fileInput(
inputId = "filedata",
label = "Upload data. csv",
multiple = FALSE,
accept = c(".csv"),
buttonLabel = "Choosing ...",
placeholder = "No files selected yet"
),
uiOutput("xvariable"),
uiOutput("yvariable")
), #sidebarpanel
mainPanel( #DTOutput("tb1"),
fluidRow(column(6, verbatimTextOutput('lmSummary')) , column(6, plotOutput('diagnosticPlot')))
)
) #fluidpage
server <- function(input, output) {
data <- reactive({
req(input$filedata)
inData <- input$filedata
if (is.null(inData)){ return(NULL) }
mydata <- read.csv(inData$datapath, header = TRUE, sep=",")
})
output$tb1 <- renderDT(data())
output$xvariable <- renderUI({
req(data())
xa<-colnames(data())
pickerInput(inputId = 'xvar',
label = 'Select x-axis variable',
choices = c(xa[1:length(xa)]), selected=xa[1],
options = list(`style` = "btn-info"))
})
output$yvariable <- renderUI({
req(data())
ya<-colnames(data())
pickerInput(inputId = 'yvar',
label = 'Select y-axis variable',
choices = c(ya[1:length(ya)]), selected=ya[2],
options = list(`style` = "btn-info"))
})
lmModel <- reactive({
req(data(),input$xvar,input$yvar)
x <- as.numeric(data()[[as.name(input$xvar)]])
y <- as.numeric(data()[[as.name(input$yvar)]])
if (length(x) == length(y)){
model <- lm(x ~ y, data = data(), na.action=na.exclude)
}else model <- NULL
return(model)
})
output$lmSummary <- renderPrint({
req(lmModel())
summary(lmModel())
})
output$diagnosticPlot <- renderPlot({
req(lmModel())
par(mfrow = c(2,2))
plot(lmModel())
})
}
shinyApp(ui = ui, server = server)
Addressing the dynamic menu:
Your selectInput element must be placed in the server section for it to be reactive. Things in the ui section are basically static. Use a uiOutput in the ui section and renderUI in the server section.
ui section (in place of selectInput block): uiOutput("var_select_ui")
server section (add):
output$var_select_ui <- renderUI({
cols <- colnames(data())
selectInput(
'vars',
'Select dependent variables',
choices = cols,
selected = cols[1:2],
multiple = TRUE
)
})

how to make data available in Rshiny?

I am trying to make data available in R shiny for survival analysis. In other words, some people might not have the access to upload data in R shiny. For those people, I want to provide some dataset so that they can use the data. Does anyone know how to make some data available in R shiny? This is the code:
library(shiny)
library(datasets)
library(survival)
options(shiny.maxRequestSize = 70 * 1024 ^ 2)
shinyUI(fluidPage(
titlePanel("Data Visualization"),
tabsetPanel(
tabPanel(
"Upload File",
titlePanel("Uploading Files"),
sidebarLayout(
sidebarPanel(
fileInput(
'file1',
'Choose RData File',
accept = c(".Rdata")
),
selectInput(
"dataset", "Select the dataset", choices = c("LUAD_RNASeq",
"LUSC_RNASeq")
)
),
mainPanel(
p("Head of the data"),
tableOutput('contents'))
)
),
tabPanel(
"Summary",
pageWithSidebar(
headerPanel('Summary of Variable'),
sidebarPanel(
# "Empty inputs" - they will be updated after the data is
uploaded
#selectInput('row', 'Row', ""),
selectInput('col', 'Column', "", selected = "")
),
mainPanel(
#p("Summary for the row"),
#verbatimTextOutput("row_summary"),
p("Summary for the column"),
verbatimTextOutput("col_summary")
)
)
),
tabPanel(
"Survival",
plotOutput("surPlot")
),
tabPanel(
"Scatter Plot",
pageWithSidebar(
headerPanel('Scatter Plot'),
sidebarPanel(
selectInput('col1', 'Column1', "", selected = ""),
selectInput('col2', 'Column2', "", selected = "")
),
mainPanel(
plotOutput("scaPlot")
)
)
),
tabPanel(
"Univariate Cox Regression",
pageWithSidebar(
headerPanel('Univariate Cox Regression'),
sidebarPanel(
selectInput('col3', 'Cox Variable', "", selected = "")
),
mainPanel(
verbatimTextOutput("reg_summary"),
plotOutput("reg_Plot")
)
)
),
tabPanel(
"AFT Regression",
pageWithSidebar(
headerPanel('Log normal AFT regression'),
sidebarPanel(
selectInput('col4', 'AFT Variable', "", selected = "")
),
mainPanel(
p("To do the AFT regression, the survival time can not be
zero"),
verbatimTextOutput("aft_summary")
#plotOutput("aft_Plot")
)
)
),
tabPanel(
"Glmnet Analysis",
p("To do Glmnetplot, the survival time can not be zero or NA
value"),
plotOutput("GlmnetPlot")
)
)
))
library(shiny)
library(datasets)
library(survival)
library(ggplot2)
library(survminer)
library(GGally)
library(glmnet)
library(rsconnect)
options(shiny.maxRequestSize = 70 * 1024 ^ 2)
load_obj <- function(f)
{
env <- new.env()
nm <- load(f, env)[1]
env[[nm]]
}
shinyServer(function(input, output, session) {
data <- reactive({
req(input$file1)
df<-load_obj(input$file1$datapath)$merged.dat
# Update inputs (you could create an observer with both updateSel...)
# You can also constraint your choices. If you wanted select only
numeric
# variables you could set "choices = sapply(df, is.numeric)"
# It depends on what do you want to do later on.
updateSelectInput(
session,
inputId = 'row',
label = 'Row',
choices = 1:nrow(df),
selected = 1
)
updateSelectInput(
session,
inputId = 'col',
label = 'Column',
choices = names(sapply(df, is.numeric)),
selected = names(df)[2]
)
updateSelectInput(
session,
inputId = 'col1',
label = 'Column1',
choices = names(sapply(df, is.numeric)),
selected = names(df)[4]
)
updateSelectInput(
session,
inputId = 'col2',
label = 'Column2',
choices = names(sapply(df, is.numeric)),
selected = names(df)[5]
)
updateSelectInput(
session,
inputId = 'col3',
label = 'Cox Variable',
choices = names(sapply(df, is.numeric)),
selected = names(df)[5]
)
updateSelectInput(
session,
inputId = 'col4',
label = 'AFT Variable',
choices = names(sapply(df, is.numeric)),
selected = names(df)[5]
)
return(df)
})
output$contents <- renderTable({
df<-data()
return (head(df[,1:10]))
})
output$row_summary <- renderPrint({
df<-data()
row<-as.numeric(df[input$row, 2:ncol(df)])
summary(row)
})
output$col_summary <- renderPrint({
df<-data()
column<-df[,input$col]
summary(column)
})
output$surPlot <- renderPlot({
plot.survival <- function(data)
{
ggsurv(survfit(
Surv(data$OS, data$status) ~ 1,
type = "kaplan-meier",
conf.type = "log-log"
),
main = "Survival Plot(K-M estimate)")
}
print(plot.survival(data()))
})
output$scaPlot <- renderPlot({
df<-data()
column1<-df[,input$col1]
column2<-df[,input$col2]
plot(column1, column2)
})
output$reg_summary <-renderPrint({
df=data()
column3=df[,input$col3]
res.cox=coxph(Surv(df$OS,df$status) ~ column3, data=df)
summary(res.cox)
})
output$reg_Plot <- renderPlot({
df=data()
column3=df[,input$col3]
res.cox=coxph(Surv(df$OS,df$status) ~ column3, data=df)
ggsurvplot(survfit(res.cox), palette = "#2E9FDF",ggtheme =
theme_minimal(),data = df)
})
output$aft_summary <-renderPrint({
df=data()
column4=df[,input$col4]
res.aft=survreg(Surv(df$OS,df$status) ~ column4, data=df,
dist="lognormal")
summary(res.aft)
})
output$GlmnetPlot <- renderPlot({
df=data()
y1=cbind(time=df$OS,status=df$statu)
x1 <- subset(df, select = -c(bcr,OS, status))
x1=data.matrix(x1, rownames.force = NA)
fit1=glmnet(x1,y1,family="cox")
plot(fit1)
})
# datasetInput <- eventReactive(input$update, {
# switch(input$dataset,
# "rock" = rock,
# "pressure" = pressure,
# "cars" = cars)
# })
# output$aft_Plot <- renderPlot({
# df=data()
# df=df[-c(which(df$OS==0)),]
# column4=df[,input$col4]
# res.aft=survreg(Surv(df$OS,df$status) ~ column4, data=df,
dist="lognormal")
# ggsurvplot(survfit(res.aft), color = "#2E9FDF",ggtheme =
theme_minimal(),data = df)
# })
})
If you have a CSV file with your data, include that in the folder your Shiny app is in, and call:
mydata <- read.csv("your_file.csv")
If you save your data as an R variable as an Rds:
mydata <- readRDS("your_file.Rds")

Select columns from expression in shiny app

I am trying to build a shiny dashboard app, where I process the input data and produce summary statistics based on the user supplied grouping variables. The last step, where I am stuck is to
implement a working function , which enables the user to select to display only a subset of the columns after the calculation of the summary statistics.
My attempt is in the lines after output$select_col in global.R . Right now each time I try to use the selector shiny crashes with the error "incorrect number of dimensions".
global.R
# Shiny
library(shiny)
library(shinydashboard)
library(shinyjs)
# Data tools
library(dplyr)
library(tidyr)
library(tibble)
library(data.table)
server.R
server <- function(input, output) {
raw_tables<-reactive({
mtcars
})
output$cyl <- renderUI({
selectInput(inputId = "cyl",
label = "Which number of cyl to consider",
choices = c(4,6,8),
selected = NULL,
multiple=TRUE)
})
filtered_tables<-
reactive({
if(is.null(input$cyl)){
data_filtered <- raw_tables()
}
else{
data_filtered <- raw_tables() %>% filter(cyl %in% input$cyl)
}
})
new_statistics <- reactive({
if(is.null(filtered_tables())){
return(NULL)
}
if(length(input$grouping_variables) == 0){
op <- filtered_tables() %>%
ungroup()
} else {
op <- filtered_tables() %>%
group_by_(.dots = input$grouping_variables)
}
op %>% #
summarise(nr_cars = n(),
mean_mpg = mean(mpg,na.rm=T),
sd_mpg = sd(mpg,na.rm=T))
})
nice_table <-reactive({
if(is.null(new_statistics())){
return(NULL)
}
DT::datatable(new_statistics(),
colnames = c(
"nbr cars"="nr_cars" ,
"mean mpg"="mean_mpg",
"sd mpg"="sd_mpg"
), selection = list(target = 'column') , extensions = c('ColReorder'), options = list(colReorder = TRUE)
) %>%
DT::formatRound(columns=c(
"nbr cars" ,
"mean mpg",
"sd mpg"),
digits=2)
})
output$select_col <- renderUI({
if(is.null(nice_table())){
return(NULL)
}
selectInput("col", "Select columns:", choices = colnames(nice_table()), selected=NULL, multiple=TRUE)
})
output$statistics = DT::renderDataTable({
if(length(input$col)>0)
{
return(DT::datatable(nice_table()[, colnames(nice_table()) %in% input$col]))
}
else
{
return(NULL)
}
})
}
ui.R
dbHeader <- dashboardHeader(title = "test",
titleWidth = 250)
sidebar <- dashboardSidebar(
width = sidebarWidth,
br(),
sidebarMenu(
menuItem(text = "Data View",
tabName = "dat_view",
icon = icon("cloud-download")
)
)
)
body <- dashboardBody(
# Add shinyJS mini-sidebar
shinyjs::useShinyjs(),
tabItems(
tabItem(tabName = "dat_view",
fluidPage(
sidebarLayout(
sidebarPanel(width=2,
selectInput(inputId = 'grouping_variables',
label = 'Which grouping var?',
choices = c("cyl","gear","carb"),
selected = NULL,
multiple=TRUE,
selectize=TRUE),
uiOutput("cyl"),
uiOutput("select_col")
)
,
mainPanel(
tabsetPanel(id="dat_view_tabs",
tabPanel(
'statistics',
DT::dataTableOutput(outputId='statistics')
)
)
)
)))))
ui <- dashboardPage(skin = "blue",
header = dbHeader,
sidebar = sidebar,
body = body)

Resources