"Warning: Error in eval: could not convert n to scalar integer" - r

I'm trying to make a shiny app that can let you choose different statistical methods to analyze some insurance data and then plot the results in a certain way. I want to be able to select a few values in the interface and the names of methods, and then have one button to trigger the creation of the model, and then another button to trigger the plot creation.
I'm pretty new to Shiny App and I'm getting an error message that I just cannot figure out.
"Warning: Error in eval: could not convert n to scalar integer"
Here is my code:
library(shiny)
library(insuranceData)
library(caret)
library(randomForest)
library(dplyr)
library(ggplot2)
library(pls)
data(AutoBi)
ui <- fluidPage(
# Application title
titlePanel("Ratemaking Tool"),
#fileInput("file", "Upload file"),
actionButton("do", "Make Model"),
actionButton("Go", "Make Graph"),
selectInput("Model", "Model", c("lm", "glm", "pls")),
sidebarLayout(
sidebarPanel(
sliderInput("percentiles",
"Percentile Splits:",
min = 1,
max = 20,
value = 5,round = TRUE),
sliderInput("cv_splits",
"Folds for K-fold validation:",
min = 1,
max = 10,
value = 5,round = TRUE)),mainPanel(plotOutput("distPlot")
)
)
)
server <- function(input, output){
values <- reactiveValues(df_data = NULL)
observeEvent(input$do, {
dataInput <- isolate(reactive({
t <- AutoBi %>% na.omit() %>% mutate(log.age = log(CLMAGE + 1),log.loss = log(LOSS + 1))
train = slice(t,1:700)
test = slice(t,701:nrow(t)) %>% mutate(log.age = log(CLMAGE + 1),log.loss = log(LOSS + 1))
t1 <- select(train,-c(log.loss,LOSS,CLMAGE))
ctrl <- isolate(trainControl(method = "cv",number = input$cv_splits))
model <- train(x = t1[,c(2,3,4,5,6,7)],y = train$LOSS,trControl = ctrl,
method = input$Model)
preds <- predict(model,test[,c(2,3,4,5,6,9)])
test$pred <- preds
ordered <- test %>% arrange(pred) %>% mutate(quantile = ntile(pred,input$percentiles)) %>% group_by(quantile) %>%
summarize(avg_loss = mean(LOSS),avg_prd= mean(pred)) %>% mutate(flag = as.factor(ifelse(avg_loss - avg_prd > 0,0,1)))
values$df_data = ordered
return(ordered)
}))
values$df_data = dataInput()
})
observeEvent(input$Go,{
output$distPlot <- isolate(renderPlot({
ggplot(values$df_data)+ aes(quantile,avg_loss,size = 1) + geom_point() + geom_point(aes(y = avg_prd,color = "avg_pred")) + ggtitle(paste("Statistical Learning Technique:", input$Model)) +
geom_linerange(aes(ymin = avg_prd,ymax = avg_loss,size = .1,color = flag)) + guides(size=FALSE)
}))
})
}
shinyApp(ui = ui, server = server)

Related

Interactive heatmap in R using apexcharter fails at reactivity

at the moment I try to create an interactive heatmap in R with apexcharter. This works fine at manual chart creation but fails on interactive use within shiny.
library(shiny)
library(tidyverse)
library(apexcharter)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Test Heatmap"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
selectInput(
inputId = "heatmap_filter",
label = "heatmap filter",
choices = c(1999, 2008),
selected = 2008
)
),
mainPanel(
apexchartOutput("heatmap")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$heatmap <- renderApexchart({
df <- mpg %>% filter(year == input$heatmap_filter) %>% mutate_if(is.character, as.factor) %>% group_by(manufacturer, class) %>% summarise(cnt = n()) %>% tidyr::complete(class, fill = list(cnt = 0))
q20 <- round(as.numeric(quantile(df %>% filter(cnt>0) %>% pull(cnt), probs = seq(0,1,0.2), na.rm = TRUE))[2],0)
q40 <- round(as.numeric(quantile(df %>% filter(cnt>0) %>% pull(cnt), probs = seq(0,1,0.2), na.rm = TRUE))[3],0)
q60 <- round(as.numeric(quantile(df %>% filter(cnt>0) %>% pull(cnt), probs = seq(0,1,0.2), na.rm = TRUE))[4],0)
q80 <- round(as.numeric(quantile(df %>% filter(cnt>0) %>% pull(cnt), probs = seq(0,1,0.2), na.rm = TRUE))[5],0)
apex(
data = df,
type = "heatmap",
mapping = aes(x = manufacturer, y = class, fill = cnt)
) %>%
ax_dataLabels(enabled = TRUE) %>%
ax_plotOptions(
heatmap = heatmap_opts(
enableShades = FALSE,
colorScale = list(
ranges = list(
list(from = 0, to = q20, color = "#106e45"), #grün
list(from = q20, to = q40, color = "#90dbba"), #leichtes grün
list(from = q40, to = q60, color = "#fff33b"), #gelb
list(from = q60, to = q80, color = "#f3903f"), # orange
list(from = q80, to = 20, color = "#e93e3a") #rot
)
)
)
) %>%
ax_title(
text = paste("Test interactive heatmap",
input$heatmap_filter
), align = "center"
)
})
}
# Run the application
shinyApp(ui = ui, server = server)
With the manual approach everthing works as expected. But when I change the input select only the values changes but not the heatmap quantil ranges and not the title input. Its seems like the input value is not pushing the changes to already calculated variables. I already tried to use an reactive df or reactive variables but so far nothing works.
I added a minimal example where you could change the year input and this should change the title and the color ranges.
Can you help me?
Thanks in advance.
Try setting auto_update to FALSE in the call to apex
apex(
data = df,
type = "heatmap",
auto_update = FALSE,
...

Shiny failed to read column based on selectInput from uploaded csv

Problem:
I was trying to build a shiny app that plot frequency of n-grams based on a user specified column from a user uploaded csv. In addition, a function was added to plot the senetiment over time, based on a date column specified by the user as well.
The app was working okay locally, with Warning, but failed work after published. Please see the following for a reproducible example.
Preparation: libraries and example data
# Load R packages
library(shiny)
library(tidyverse)
library(shinythemes)
library(lubridate)
library(tidytext)
library(textdata)
# Creating a example csv file for upload
Sample_csv <-
data.frame(text = janeaustenr::emma,
id = 1:length(janeaustenr::emma),
date = sample(seq(as.Date('1900/01/01'), as.Date('1920/01/01'), by="day"),
replace = T,
length(janeaustenr::emma)))
write.csv(Sample_csv, "Sample_csv.csv", row.names = F)
UI
ui <- fluidPage(theme = shinytheme("united"),
titlePanel("Text glancer"),
sidebarLayout(
sidebarPanel(
# Input: Select a file ----
fileInput("csv_file", "Feed csv here",
multiple = FALSE,
accept = c(".csv")),
#Conditional panel
conditionalPanel(
# use a server side condition
condition = "output$fileUploaded",
# Input: Select ----
uiOutput("text_select"),
# Input: Select ----
uiOutput("date_select"),
# Input: Simple integer interval ----
sliderInput("top_frequency", "Top n ngrams to be plotted:",
min = 5, max = 20, value = 10),
# Input: Select ----
selectInput("ngrams", "Ngrams of your choice:",
c("Single word" = 1,
"Bigram" = 2,
"Trigram" = 3)
)
),
# Submit bottom
submitButton("Update View", icon("refresh"))
),
# sidebarPanel
mainPanel(
tabsetPanel(
tabPanel(h2("Most frequenlty used n-grams"),
plotOutput("frequency_plot", height = 900, width = 1200)),
tabPanel(h2("Sentiment of the months"),
plotOutput("sentiment_plot", height = 900, width = 1200))
)
)
)
)
server
server <- function(input, output, session) {
# create reactive version of the dataset (a data.frame object)
LOAD_DATA <- reactive({
infile <- input$csv_file
if (is.null(infile))
{return(NULL)}
{read_csv(infile$datapath)}
})
# inform conditionalPanel wheter dropdowns sohould be hidden
output$fileUploaded <- reactive({
return(!is.null(LOAD_DATA()))
})
outputOptions(output, 'fileUploaded', suspendWhenHidden=FALSE)
## update 'column' selectors
output$text_select <- renderUI({
if(is.null(LOAD_DATA()))
{return(NULL)}
else
selectInput("text_col", "Select the text column:", colnames(LOAD_DATA()))
})
output$date_select <- renderUI({
if(is.null(LOAD_DATA()))
{return(NULL)}
else
selectInput("date_col", "Select the date column (ymd):", colnames(LOAD_DATA()))
})
# Create reactive parameters
TOP_FREQUENCY <- reactive({
input$top_frequency
})
N_GRAMS <- reactive({
as.numeric(as.character(input$ngrams))
})
# Output frequency of ngrams
output$frequency_plot <- renderPlot( {
if(is.null(LOAD_DATA()))
{return(NULL)}
else{
WORK_DATA <- LOAD_DATA()[,c(input$text_col,
input$date_col)]
names(WORK_DATA) <- c("TEXTS", "DATES")
CSV_DOC_N_Grams <-
WORK_DATA %>%
# LOAD_DATA() %>%
# select(TEXTS = TEXT_COL(), DATES = DATE_COL()) %>%
mutate(TEXTS = gsub("http.*", " ", TEXTS)) %>%
# mutate(text = gsub("\\#.* |\\#.* .|\\#.* ,", " ", text)) %>%
unnest_tokens(words, TEXTS, token = "ngrams", n = N_GRAMS()) %>%
select(words) %>%
filter(str_detect(words, "[a-zA-Z]")) %>%
separate(words, c("word1","word2","word3"),sep = " ", remove = F) %>%
filter(! word1 %in% stop_words$word &
! word2 %in% stop_words$word&
! word3 %in% stop_words$word)
#Counting ngrams
CSV_DOC_N_Gramss_Count <-
CSV_DOC_N_Grams %>%
count(words, sort=T) %>%
select(N_Gram_Text = words,
N_Gram_Count = n)
#Plotting ngram frequency
CSV_DOC_N_Gramss_Count_freq <-
CSV_DOC_N_Gramss_Count %>%
mutate(N_Gram_Text = fct_reorder(N_Gram_Text, N_Gram_Count)) %>%
top_n(TOP_FREQUENCY(), N_Gram_Count) %>%
ggplot(aes(x = N_Gram_Text,
y = N_Gram_Count,
fill = N_Gram_Count)) +
geom_col()+
coord_flip() +
scale_fill_gradient2()+
labs(title = paste0("Top ", TOP_FREQUENCY(), " ngrams used in csv doc"),
x = "ngrams",
y = "frequency") +
theme_bw()+
theme(legend.position = "none",
axis.text.x = element_text(face='bold',size=12),
axis.text.y = element_text(face='bold',size=12),
axis.title.x = element_text(face='bold',size=18),
axis.title.y = element_blank())
print(CSV_DOC_N_Gramss_Count_freq)
}
})
output$sentiment_plot <- renderPlot( {
if(is.null(LOAD_DATA())){return(NULL)}
else{
WORK_DATA <- LOAD_DATA()[,c(input$text_col,
input$date_col)]
names(WORK_DATA) <- c("TEXTS", "DATES")
tk_afinn <-
WORK_DATA %>%
mutate(TEXTS = gsub("http.*", " ", TEXTS)) %>%
unnest_tokens(word, TEXTS) %>%
filter(! word %in% stop_words$word) %>%
filter(str_detect(word, "[a-zA-Z]")) %>%
filter(! DATES %in% NA) %>%
inner_join(get_sentiments("afinn")) %>%
mutate(YEAR_Month = ymd(paste(year(DATES),
month(DATES),
"1", sep="-"))) %>%
group_by(index = YEAR_Month) %>%
summarise(sentiment = sum(value))
tk_afinn_plot <-
tk_afinn %>%
ggplot(aes(x = index, y = sentiment)) +
geom_line()+
labs(x = "date (year-month)",
y = "sentiment of the month") +
theme_bw()+
theme(legend.position = "none",
axis.text.x = element_text(face='bold',size=12),
axis.text.y = element_text(face='bold',size=12),
axis.title.x = element_text(face='bold',size=18),
axis.title.y = element_blank())
print(tk_afinn_plot)
}
})
}
Fuse
shinyApp(ui = ui, server = server)
Warnings:
After loading the csv file, the local app reports :
"Problem with mutate() input TEXTS.
object 'TEXTS' not found
Input TEXTS is gsub("http.*", " ", TEXTS)."
After specify the text column and date column, both tab showed plots. However, after publishing it to shinyapp.io, it reports error and would not run.
Can anybody help with this issue? I have consulted the other thread includin this>https://stackoverflow.com/questions/47248534/dynamically-list-choices-for-selectinput-from-a-user-selected-column, but still no luck.
Any insight would be greatly appreciated!

Why does ggplotly lose my scale_size_continuous legend?

I am developing a Shiny app to interactively display a bubbleplot using ggplot2, and I would like to add plotly functionality to it. The following creates data for a reproducible example:
# Load packages
library(shiny)
library(shinythemes)
library(tidyverse)
# create data
Name <- c(rep(c("Red Pine", "Sugar Maple"), each = 125))
mean.SDI <- c(rnorm(250, 150, 150))
mean.SDI <- mean.SDI + abs(min(mean.SDI))
DI <- c(rep(c(rep(c(1:5), 25)), 2))
PI <- c(rep(c(rep(c(1:5), each = 25)), 2))
GrowthRate <- c(rnorm(250, 2.5, 1))
GrowthRate[GrowthRate < 0] <- 0
n <- as.integer(runif(250, min = 1, max = 50))
trend_data <- tibble(Name, mean.SDI, DI, PI, GrowthRate, n)
The following script that DOES NOT use plotly produces the desired result:
# Define UI
ui <- fluidPage(theme = shinytheme("lumen"),
titlePanel("Growth rates"),
sidebarLayout(
sidebarPanel(
selectInput(inputId = "Species", label = strong("Species"),
choices = unique(trend_data$Name)[order(unique(trend_data$Name))],
selected = "Red Pine"),
sliderInput(inputId = "SDI", label = strong("Stand density index"),
min = 0, max = 1100, value = c(0, 800), dragRange = TRUE)
),
mainPanel(
fluidRow(column(6, plotOutput(outputId = "bubbleplot", height = "400px", width = "600px"))
)
)
)
)
# Define server function
server <- function(input, output) {
# Subset data
DI_PI <- reactive({
trend_data %>%
filter(
Name == input$Species,
mean.SDI >= input$SDI[1] & mean.SDI <= input$SDI[2]
) %>%
group_by(DI, PI) %>%
summarize(GrowthRate = mean(GrowthRate),
n = as.numeric(sum(n))) %>%
mutate(nAlpha = n > 50)
})
# Create scatterplot object the plotOutput function is expecting
output$bubbleplot <- renderPlot({
p <- ggplot(DI_PI(), aes(x = DI, y = PI, size = GrowthRate, alpha = nAlpha)) +
geom_point(col = '#236AB9') +
xlab("DI Class") +
ylab("PI Class") +
coord_cartesian(xlim = c(1, 5), ylim = c(1,5)) +
scale_size_continuous(name = "Subplot-level Growth Rate \n (ft2 per acre per year)",
range = c(0.1, 15)) +
scale_alpha_discrete(labels = c("Less than 50 subplots", "At least 50 subplots"),
name = "")
print(p)
})
}
# Create Shiny object
shinyApp(ui = ui, server = server)
However, when I add plotly to this (because I want the plots to be interactive), I lose the size legend:
# Define UI
ui <- fluidPage(theme = shinytheme("lumen"),
titlePanel("Growth rates"),
sidebarLayout(
sidebarPanel(
selectInput(inputId = "Species", label = strong("Species"),
choices = unique(trend_data$Name)[order(unique(trend_data$Name))],
selected = "Red Pine"),
sliderInput(inputId = "SDI", label = strong("Stand density index"),
min = 0, max = 1100, value = c(0, 800), dragRange = TRUE)
),
mainPanel(
fluidRow(column(6, plotlyOutput(outputId = "bubbleplot", height = "400px", width = "600px"))
)
)
)
)
# Define server function
server <- function(input, output) {
# Subset data
DI_PI <- reactive({
trend_data %>%
filter(
Name == input$Species,
mean.SDI >= input$SDI[1] & mean.SDI <= input$SDI[2]
) %>%
group_by(DI, PI) %>%
summarize(GrowthRate = mean(GrowthRate),
n = as.numeric(sum(n))) %>%
mutate(nAlpha = n > 50)
})
# Create scatterplot object the plotOutput function is expecting
output$bubbleplot <- renderPlotly({
p <- ggplot(DI_PI(), aes(x = DI, y = PI, size = GrowthRate, alpha = nAlpha)) +
geom_point(col = '#236AB9') +
xlab("DI Class") +
ylab("PI Class") +
coord_cartesian(xlim = c(1, 7), ylim = c(1,5)) +
scale_size_continuous(name = "Subplot-level Growth Rate \n (ft2 per acre per year)",
range = c(0.1, 15)) +
scale_alpha_discrete(labels = c("Less than 5 subplots", "At least 5 subplots"),
name = "")
ggplotly(p)
})
}
# Create Shiny object
shinyApp(ui = ui, server = server)
It seems that ggplotly has had issues with displaying legends. Is anyone aware of a good solution to this for the "scale_size" type of legends?
Using RStudio version 1.1.453 and plotly v 4.8.0
R info:
platform x86_64-w64-mingw32
arch x86_64
os mingw32
system x86_64, mingw32
status
major 3
minor 5.0
year 2018
month 04
day 23
svn rev 74626
language R
version.string R version 3.5.0 (2018-04-23)
nickname Joy in Playing
********EDIT: tried removing "alpha" aesthetic to restrict to only one legend (for "size"), but now there is no legend plotted at all:
# EDIT server function
server <- function(input, output) {
# Subset data
DI_PI <- reactive({
trend_data %>%
filter(
Name == input$Species,
mean.SDI >= input$SDI[1] & mean.SDI <= input$SDI[2]
) %>%
group_by(DI, PI) %>%
summarize(GrowthRate = mean(GrowthRate),
n = as.numeric(sum(n))) %>%
mutate(nAlpha = n > 50)
})
# Create scatterplot object the plotOutput function is expecting
output$bubbleplot <- renderPlotly({
p <- ggplot(DI_PI(), aes(x = DI, y = PI,
#alpha = nAlpha,
size = GrowthRate)) +
geom_point(col = '#236AB9') +
xlab("DI Class") +
ylab("PI Class") +
coord_cartesian(xlim = c(1, 7), ylim = c(1,5)) +
scale_size_continuous(name = "Subplot-level Growth Rate \n (ft2 per acre per year)",
range = c(0.1, 15)) #+
#scale_alpha_discrete(labels = c("Less than 5 subplots", "At least 5 subplots"),
#name = "")
ggplotly(p)
})
}
# Create Shiny object
shinyApp(ui = ui, server = server)

plot_ly plot from dplyr breaks down at input from Shiny SelectInput

I'm just learning Shiny.
Here's the code that doesn't work (along with some sample data built-in):
library(tidyverse)
library(shiny)
library(plotly)
library(shinyjs)
analysis_df<- data.frame(
report_month = c("jan","jan","jan","jan","jan","jan"),
payee_id = c("59","59","59","59","59","59"),
Payee = sample(LETTERS[1:5],6,replace = TRUE),
Attrib_1 = sample(LETTERS[6:10],6,replace = TRUE),
Attrib_2 = sample(LETTERS[11:15],6,replace = TRUE),
country_of_sale_iso2 = c("AU","AU","AU","NZ","AU","AU"),
currency = c("USD","USD","USD","USD","USD","USD"),
Attrib_3 = c("Pandora-AU","Pandora-AU","Pandora-AU","Pandora-AU","Pandora-AU","Pandora-AU"),
month_paid = c("jun","jun","jun","jun","jun","jun"),
Attrib_4 = sample(LETTERS[16:20],6,replace = TRUE),
Attrib_5 = sample(LETTERS[21:25],6,replace = TRUE),
units = c("2","8","6","2","10","4"),
gross = c("0.003254785","0.013019141","0.009764356","0.003254785","0.016273926","0.00650957"),
reserves_wh = c("0","0","0","0","0","0"),
rsrv_liq = c("0","0","0","0","0","0"),
Attrib_7 = c("0.002753548","0.011014193","0.008260645","0.002753548","0.013767741","0.005507097"),
Attrib_8 = c("3.25E-04","0.001301914","9.76E-04","3.25E-04","0.001627393","6.51E-04"),
Attrib_9 = c("1.76E-04","7.03E-04","5.27E-04","1.76E-04","8.79E-04","3.52E-04"),
Attrib_10 = c("0.03","0.03","0.03","0.03","0.03","0.03"),
Attrib_11 = c("1","1","1","1","1","1"),
Attrib_12 = c("0.003254785","0.013019141","0.009764356","0.003254785","0.016273926","0.00650957")
)
attribs <- c("Attrib_1","Attrib_2","Attrib_3","Attrib_4")
payees <- analysis_df %>% distinct(Payee) %>% as.vector()
ui <- fluidPage(
headerPanel("Product Explorer"),
sidebarPanel(
selectInput('slice_by', 'Color the Bars By:', choices = attribs, selected = "Attrib_1"),
sliderInput('plotHeight', 'Adjust Chart Size',
min = 100, max = 2000, value = 425)
),
mainPanel(
plotlyOutput('Plot', height = "900px")
)
)
server <- function(input, output) {
output$Plot <- renderPlotly({
col_cht <- analysis_df %>%
filter(payee_id == 59) %>%
plot_ly(x = ~report_month,
y = ~gross) %>%
add_bars(color = input$slice_by) %>%
layout(barmode = "stack",
height = input$plotHeight)
})
}
shinyApp(ui, server)
I want the SelectInput to work, and it doesn't.
However, if I replace
add_bars(color = input$slice_by) %>%
with
add_bars(color = ~Attrib_1) %>%
i.e., hard-code it, the plot looks the way it should.
When you are piping with
> analysis_df %>%
the analysis_df dataframe is passed to the functions. So when using ~Attrib_1 you are passing the values in the Attrib_1 column, which are
# > analysis_df$Attrib_1
# [1] H J J H H G
So the plot gets different colors for the levels in analysis_df$Attrib_1.
When you are using input$slice_by that returns only one value, the value selected in Select. So you are getting just one color in the plot.
To get it to work use
color = analysis_df[, input$slice_by]
If you don't want to use analysis_df inside pipe, search about Non-standard Evaluation in R. With lazyeval you can do this,
color = interp(~x, x = as.name(input$slice_by))

Subsetting dataset using multiple entries in Shiny gives incorrect output

I'm creating a Shiny application and I've run into a problem when choosing multiple inputs in a selectizeInput box and trying to subset my data using those choices.
Here is the intended output
testDT <- data.table(
L = (1:32),
M = rep(letters[23:26], each = 64),
N = rep(LETTERS[1:2], times = 2, each = 512),
O = rnorm(2048, 1))
testDT$L <- factor(testDT$L, levels = seq(from = 1, to = 32, by = 1))
ggplot(testDT, aes(L,O)) +
geom_boxplot(aes(fill = N)) +
theme_bw() +
theme(legend.position = "top", legend.title=element_blank()) +
facet_grid(M ~ ., scales = "free") +
labs(x = "L", y = "O")
However, when I create the application, the graph output is not as intended. The more options I select, for example in N, it seems as if the data begins to alternate.
Here's the ui.R file:
# ui.R
shinyUI(fluidPage(
titlePanel("Test Application"),
sidebarLayout(
sidebarPanel(
selectizeInput("N",
label = ("N"),
multiple = TRUE,
choices = NULL,
options = list(
placeholder = 'Select All Desired, Type to Search',
onInitialize = I('function() { this.setValue(""); }')
)),
selectizeInput("M",
label = "M",
multiple = TRUE,
choices = NULL,
options = list(
placeholder = 'Select All Desired, Type to Search',
onInitialize = I('function() { this.setValue(""); }')
))
),
mainPanel(
tabsetPanel(
tabPanel("Test Plot 1",
plotOutput("testPlot1")),
tabPanel("Test Plot 2",
plotOutput("testPlot2"))
)
))))
And here is the server.R file:
# server.R
library(data.table)
library(ggplot2)
testDT <- data.table(
L = (1:32),
M = rep(letters[23:26], each = 64),
N = rep(LETTERS[1:2], times = 2, each = 512),
O = rnorm(2048, 1))
testDT$L <- factor(testDT$L, levels = seq(from = 1, to = 32, by = 1))
shinyServer(function(input, output, session) {
updateSelectizeInput(session, "N",
server = TRUE,
choices = sort(unique(testDT$N)),
)
updateSelectizeInput(session, "M",
server = TRUE,
choices = unique(testDT$M),
)
testDT1 <- reactive({
subset(testDT, N == input$N)
})
testDT2 <- reactive({
subset(testDT, N == input$N & M == input$M)
})
output$testTable <- renderDataTable(testDT1())
output$testPlot1 <- renderPlot({
p <- ggplot(testDT1(), aes(L,O)) +
geom_boxplot(aes(fill = N)) +
theme_bw() +
theme(legend.position = "top", legend.title=element_blank()) +
facet_grid(M ~ ., scales = "free") +
labs(x = "L", y = "O")
print(p)
})
output$testPlot2 <- renderPlot({
p <- ggplot(testDT2(), aes(L,O)) +
geom_boxplot(aes(fill = N)) +
theme_bw() +
theme(legend.position = "top", legend.title=element_blank()) +
facet_grid(M ~ ., scales = "free") +
labs(x = "L", y = "O")
print(p)
})
})
I have a strong suspicion that I am subsetting the data incorrectly, but as I am new to the Shiny environment, I don't fully understand the behavior when subsetting using an input$_____ call, like below.
testDT1 <- reactive({
subset(testDT, N == input$N)
})
I would recommend to use subsetting from [ operator instead of subset function.
Read SO question In R, why is [ better than subset? for more details on that.
In your example:
testDT1 <- reactive({
testDT[eval(call("==", as.name("N"), input$N))]
})
Change == to %in% for multi value subset.
Also be aware it may be worth to use data.table index as it can dramatically speed up filtering, so gives real-time filtering for your shiny application. For more details see my blog post Scaling data.table using index.
In fact index should be created automatically during the first filtering, you may prepare it after loading your dataset with set2keyv function.

Resources