Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

performing operations after uploading a CSV file in shiny [R]

I have made a upload button via which I am uploading a .CSV file[dataset] in shiny.

dataframe <- data.frame(A=c(2,3,4,5,6,7,3,7,8,9,2),B=c(3,7,8,9,2,1,2,3,4,5,6),C=c(1,1,1,2,2,1,1,1,1,2,2))

In ui.R :

fileInput('datafile', 'Choose CSV file',
     accept=c('csv', 'comma-separated-values','.csv')),
     actionButton("uploaddata", "upload"),

I want to perform operations such as "a+b" and "a-b" over the dataset and add it as a new column in my dataset with the help of actionButton.

Problem 1: I tried to use tableOutput() function to display the DATA in shinyapp but it is displaying DATA dataframe in R console instead.

In server.R:

DATA <- dataframe %>% group_by(C) %>% mutate(A) %>% 
mutate(B) %>% mutate(add = (A+B)) %>% mutate(sub = (A-B))

Problem 2: I want to use DATA as an input for making ggplots of (add, sub)

like image 430
ayush Avatar asked Feb 09 '23 12:02

ayush


1 Answers

You could do something like this:

ui.R

library(shiny)

shinyUI(fluidPage(
        fileInput('datafile', 'Choose CSV file',
                accept=c('csv', 'comma-separated-values','.csv')),
        tableOutput('table'),
        plotOutput('plot')
        ))

server.R

library(shiny)
library(ggplot2)

shinyServer(function(input, output,session) {

        dataframe<-reactive({
                if (is.null(input$datafile))
                        return(NULL)                
                data<-read.csv(input$datafile$datapath)
                data<- data %>% group_by(C) %>% mutate(A) %>% 
                        mutate(B) %>% mutate(add = (A+B)) %>% mutate(sub = (A-B))
                data
        })
        output$table <- renderTable({
                dataframe()
        })
        output$plot <- renderPlot({
                if(!is.null(dataframe()))
                        ggplot(dataframe(),aes(x=X,y=add))+geom_point()
        })
})

I removed the action button because fileInput will load the file directly once the user has chosen it. In the server.R, the loaded dataframe is stored in a reactive value, you can call dataframe() when you want to make a plot/render the table to get the dataframe.

You might also want to code to check that your csv file has A and B as column etc.

like image 159
NicE Avatar answered Feb 12 '23 05:02

NicE