I would like to select some rows of a dataset given an input defined by the user. In this case I would like to run different classification trees depending on the different positions in the field. I have a selectInput() in Shiny R which expands a menu where you can select for which field position you want to run the tree. However, for the moment it only runs for all the positions but not for each one individually. I'd appreciate some help on how to switch between datasets depending on user selection.
server.R
library(shiny)
library("rpart")
library("party")
library("partykit")
setwd("~/UNIVERSIDAD/EUR/Block 2/Machine Learning/Shiny App Both")
dat <- read.csv("Voetballers.csv")
dat <- dat[,3:20]
shinyServer(function(input, output, session) {
observe({
if(input$position=="All"){
dat <- dat
}
else if(input$position=="Forward"){
dat <- dat[dat$Position=="Forward",]
}
else if(input$position=="Midfielder"){
dat <- dat[dat$Position=="Midfielder",]
}
else if(input$position=="Defender"){
dat <- dat[dat$Position=="Defender",]
}
else if(input$position=="Goalkeeper"){
dat <- dat[dat$Position=="Goalkeeper",]
}
})
output$independent <- renderUI({
checkboxGroupInput("independent", "Independent Variables:",names(dat)[!names(dat) %in% input$dependent],names(dat)[!names(dat) %in% input$dependent])
})
runRegression <- reactive({
ctree(as.formula(paste(input$dependent," ~ ",paste(input$independent,collapse="+"))),data=dat)
})
runRegression2 <- reactive({
rpart(as.formula(paste(input$dependent," ~ ",paste(input$independent,collapse="+"))),data=dat)
})
output$plot1 <- renderPlot({
plot(runRegression())})
output$plot2 <- renderPlot({
plot(as.party(runRegression2()))})
})
Related
I am new to r and shinny, and can't figure out how to fix my code. I have 2 dfs (df and historical), and I filter the df to display results selected from SelectInput (col, and col2, "Market" and "Month"). At the same time, I want to filter historical by the same values choosen for "Market" and "Month", and display below the table, a histogram of the filtered price_vector - that is, "average_price" from "historical" but filtered by chosen "Market" and "Month".
Any feedback is appreciated, and by the way, if you have a solution that uses reticulate, I dont mind it (no problem for me filtering a df using python/pandas, but I am teaching myself shinny and can't figure this out)
library(shiny)
library(reticulate)
df <- read.csv(file = 'scores.csv')
historical <- read.csv('TRAIN.csv')
price_vector <- historical$average_price
lmkt <- unique(df$market)
mth <- unique(df$month)
ui <- fluidPage(
selectInput('col','Market',lmkt),
selectInput('col2','Month',mth),
dataTableOutput('table')
)
server <- function(input,output)
output$table <- renderDataTable({
df <- df
{
df = df[df[["market"]] == input$col,]
df = df[df[["month"]] == input$col2,]
}
})
shinyApp(ui = ui, server = server)
You can combine the two statements into one using & operator.
df <- read.csv('https://raw.githubusercontent.com/lmsanch/pyABS/master/scores.csv')
historical <- read.csv('https://raw.githubusercontent.com/lmsanch/pyABS/master/TRAIN.csv')
price_vector <- historical$average_price
lmkt <- unique(df$market)
mth <- unique(df$month)
ui <- fluidPage(
selectInput('col','Market',lmkt),
selectInput('col2','Month',mth),
dataTableOutput('table'),
plotOutput('plot')
)
server <- function(input,output) {
output$table <- renderDataTable({
df[df$market == input$col & df$month == input$col2, ]
})
output$plot <- renderPlot({
hist(price_vector[df$market == input$col & df$month == input$col2])
})
}
shinyApp(ui, server)
I am continuing my struggles through R & R Shiny and have a question. I have a list of data frames. I want to use the names of the data frames from this list, to populate selectInput, and based on the selection of the data frame, I want to be able to view selected data frame, and see the statistics of its columns.
So far I have found this code
shinyServer(function(input, output) {
reactive_df <- reactive({
if(input$x=="All")
return df
else
return(select(df, starts_with(input$x)))
}
output$x <- renderDataTable(reactive_df())
}
But it does not do exactly what I want. Does anyone know how to create the table and the summaries?
You could have a look at mastering shiny:
ui <- fluidPage(
selectInput("dataset", label = "Dataset", choices = ls("package:datasets")),
verbatimTextOutput("summary"),
tableOutput("table")
)
server <- function(input, output, session) {
output$summary <- renderPrint({
dataset <- get(input$dataset, "package:datasets")
summary(dataset)
})
output$table <- renderTable({
dataset <- get(input$dataset, "package:datasets")
dataset
})
}
shinyApp(ui=ui,server=server)
If you have your own list of dataset, you can use [[...]] instead of get:
datasetlist <- list(iris = iris, mtcars = mtcars)
data <- datasetlist[[input$datasetname]]
for example if input$datasetname=='iris', you can check that this will assign iris to data for further processing:
data <- datasetlist[["iris"]]
data
Another option is :
data <- eval(parse(text=input$datasetname))
I would like to update the content of a reactive object that is holding a tibble in response to a button push and I can't figure out the syntax. The solution that was posted here contains a solution that used to work but now it throws an error.
Below is a reprex of the issue I am having. Run the write.csv(iris, "text.csv") first.
library(shiny)
library(tidyverse)
# create the test data first
# write.csv(iris, "text.csv")
server <- shinyServer(function(input, output) {
in_data <- reactive({
inFile <- input$raw
x <- read.csv(inFile$datapath, header=TRUE)
})
subset <- reactive({
subset <- in_data() %>%
filter(Species == "setosa")
})
observeEvent(input$pushme, {
subset()$Sepal.Length[2] <- 2
})
output$theOutput <- renderTable({
subset()
})
})
ui <- shinyUI(
fluidPage(
fileInput('raw', 'Load test.csv'),
actionButton("pushme","Push Me"),
tableOutput('theOutput')
)
)
shinyApp(ui,server)
My code to change the value:
subset()$Sepal.Length[2] <- 2
Throws this error:
Error in <-: invalid (NULL) left side of assignment
What is the syntax for programmatically changing the value in a reactive tibble?
You can't modify directly the value of a reactive object. You have to define first a static object that will take the value of the reactive object, and then you can modify the value of the static object. Two options for you (no modifications in ui):
The first one is to use renderTable just after having subseted your data, and then to modify your table inside observeEvent:
server <- shinyServer(function(input, output) {
in_data <- reactive({
inFile <- input$raw
x <- read.csv(inFile$datapath, header=TRUE)
})
test1 <- reactive({
data <- in_data() %>%
filter(Species == "setosa")
data
})
output$theOutput <- renderTable({
req(input$raw)
test1()
})
observeEvent(input$pushme, {
output$theOutput <- renderTable({
req(input$raw)
test1 <- test1()
test1$Sepal.Length[2] <- 2
test1
})
})
})
The second one is to define another dataset (test2 here) that will be computed with eventReactive only if the button is pushed. Then you have to define which of the two datasets you want to use in renderTable using conditions on their existence:
server <- shinyServer(function(input, output) {
in_data <- reactive({
inFile <- input$raw
x <- read.csv(inFile$datapath, header=TRUE)
})
test1 <- reactive({
data <- in_data() %>%
filter(Species == "setosa")
data
})
test2 <- eventReactive(input$pushme, {
test1 <- test1()
test1$Sepal.Length[2] <- 2
test1
}
)
output$theOutput <- renderTable({
if (input$pushme) {
test2()
}
else {
req(input$raw)
test1()
}
})
})
By the way, you shouldn't call datasets (reactive or not) like function names. In your example, you have called subset the reactive dataset you modify. This is not good since this dataset will be used as subset() (because it is reactive). It may be confusing both for you and for the execution of the code.
I am doing the following:
using R ShinyUI, get client inputs on ranges of variables A, B, C;
in R ShinyServer, read in a csv file, and using the client inputs to slice the csv, and get the portion that I need;
Perform a loop calculation on the csv, calculate various statistics from the loop output, and plot all these statistics.
Pseudo code:
data = read.csv('file.csv')
shinyServer(function(input, output) {
data <- reactive({
data = data[data$A<INPUT1 & data$B> INPUT2 & data$C<INPUT3,]
})
for (i in 1:dim(data)[1]){
result1[i] = xxx
result2[i] = xxx
}
output$plot <- renderPlot({
plot(result1)
})
})
The above code does not work. I want to know:
How to correctly incorporate user input and get the variable "data,"
How to plot result1 and result2 from output$plot
Thanks!
The for loop should be inside a the renderPlot, so each time the input$month changes, the reactive data will change and then the for lop will update your variables. If you have the for loop outside a reactive expression, it will be executed only once when the app starts, but after changes in the input.
Below is simple example based on the pseudo code you provide in your original question to illustrate the possible solution.
library(shiny)
ui <- shinyUI( fluidPage(
fluidRow(
column(4,
numericInput("input1", "Speed >", 8),
numericInput("input2", "Dist >", 15)
),
column(8,
plotOutput("plot")
)
)
))
server <- shinyServer(function(input, output) {
dat0 <- cars
data <- reactive({
dat0[dat0$speed > input$input1 & dat0$dist > input$input2,]
})
output$plot <- renderPlot({
s <- dim(data())[1]
result1 <- numeric(s)
result2 <- numeric(s)
for (i in 1:s){
result1[i] <- data()[i, 1]
result2[i] <- data()[i, 2]
}
plot(result1, result2)
})
})
shinyApp(ui = ui, server = server)
I would like to chose one of regression models from a selection of different kind of models and, then, apply it to a subset. But I've difficult to understand how I can paste the function in server.R
Here there is a part of code in ui.R
h3("Model Prediction"),
selectInput("regression", "Select Model:",
list("y~x",
"y~x^2")
In server.R I've written this code
dati<- as.data.frame( read.csv(file='file.csv', header=TRUE, sep=";", dec=","))
mydata <- reactive({
(pdata=subset(dati,index==input$proj))
})
shinyServer(function(input, output) {
#Simple plot
output$testPlot = renderPlot({
pdata=subset(dati,index==input$proj)
plot(pdata$gg, pdata$y )
})
###my data
mydata <- reactive({
(pdata=subset(dati,index==input$proj))
})
runRegression <- reactive({
lm(as.formula(paste(input$dependent," ~ ",paste(input$independent,collapse="+"))),data=dat)
})
})
You can try to use sprintf for it
like
selectInput("regression", "Select Model:",
list("y~x"="%s",
"y~x^2"="%s^2"))
as.formula(paste(input$dependent," ~ ",paste(sprintf(fmt = input$regression,input$independent),collapse="+")))