Larry Larry - 4 months ago 57
R Question

R shiny render UI does not work

In my application, I ask the user to input a file (.csv). Further there are two selectInput(s) which are populated with column names from the input file using renderUI(). As user selects two different columns and click submitButton a plot is generated. The UI with ideal output is given below. This works because i have manually input the values in plot and it does not take the columns as selected in drop down options.

correct output

enter image description here

I think the problem is converting factor type elements in dataframe to numeric type which can be plotted.

the error image :

enter image description here

server.R

library(shiny)
shinyServer(function(input, output) {

lastgang <- reactive({
if(is.null(input$file)){return()}
read.table(file=input$file$datapath, header =TRUE, sep=",")
})

output$X = renderUI({
selectInput("X", "Select field to plot along X axis", names(lastgang()), selected = NULL)
})

output$Y = renderUI({
selectInput("Y", "Select field to plot along Y axis", names(lastgang()), selected = NULL)
})

output$plot <- renderPlot({
if (is.null(input$X) || is.null(input$Y)){return()}
x = input$X
y = input$Y
plot(as.numeric(lastgang()$x),as.numeric(lastgang()$y))
})
})


ui.R

library(shiny)

shinyUI(fluidPage(

titlePanel("Source Design"),
sidebarLayout(
sidebarPanel(fileInput("file", label = h4("Select *.csv file")),

uiOutput("X"),
uiOutput("Y"),
submitButton("Plot")
),

mainPanel(
plotOutput('plot') )
)
))

Answer

If x and y are strings and lastgang is a dataframe. Then your error does not have any to do with the use of shiny. The following do not work in R

> D <- data.frame(Col1=1:5, Col2=11:15)
> a <- 'Col1'
> b <- D$a
> b
NULL

This is because after $ R expects a column name of the data frame. If the variable before $ is a data frame, then you got NULL if the column name does not exist. You want the column called Col1

> D <- data.frame(Col1=1:5, Col2=11:15)
> a <- 'Col1'
> b <- D[, which(names(D) == a)]
> b
[1] 1 2 3 4 5