I'm working on a shiny app to manipulate data.
I'd like to read a zip file selectioned in a fileInput. This zip is composed by multiple csv files, and I'd like to save as reactive values all .csv dataframes.
For example, if test.zip contains file ONE.csv, TWO.csv, THREE.csv , i'd like to obtain 3 reactives values (as dataframes) called ONE , TWO, THREE .
I'm abble to do it if I know the name and number of csv files.
But if I don't know the number and names of .csv dataframes, how can I achieve it ?
## Only run examples in interactive R sessions
if (interactive()) {
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput("ZIP", "Choose ZIP File",
accept = ".zip"
)
),
mainPanel(
DT::dataTableOutput("ONEtab")
)
)
)
server <- function(input, output) {
ONE <- reactive({
inFile <-req(input$ZIP)
read_csv(unzip(inFile$datapath,"ONE.CSV"))
})
TWO <- reactive({
inFile <-req(input$ZIP)
read_csv(unzip(inFile$datapath,"TWO.CSV"))
})
THREE <- reactive({
inFile <-req(input$ZIP)
read_csv(unzip(inFile$datapath,"THREE.CSV"))
})
output$ONEtab <- DT::renderDataTable({ DT::datatable(ONE(), option=list(scrollX=T),filter = 'top')})
}
shinyApp(ui, server)
}
Thanks for your help !
One option is to read all the dataframes into a single variable and then use a number to select the one of interest. Here's some code that does this. It uses lapply to read the contents of the zip file to create a reactive variable called all. To reference different dataframes, the code required is all()[[index]] and I have added something that shows this.
library(DT)
library(readr)
ui <- fluidPage(sidebarLayout(sidebarPanel(
fileInput("ZIP", "Choose ZIP File", accept = ".zip"),
selectInput("choice", 'Choose', choices = c(1,2,3), selected = 1)
),
mainPanel(DT::dataTableOutput("selectone"))))
server <- function(input, output) {
all <- reactive({
inFile <- req(input$ZIP)
filelist <- unzip(inFile$datapath, list = T)
lapply(filelist$Name, read_csv)
})
output$selectone <-
DT::renderDataTable({
choice = as.integer(input$choice)
DT::datatable(all()[[choice]], option = list(scrollX = T), filter = 'top')
})
}
shinyApp(ui, server)
Without the rest of your code that processes this, it's difficult to know if this will be what you need but perhaps it's a start.
Related
I'm pretty stuck here; I have created a simple shiny app with the possibility of uploading multiple files. However, I don't know how can I move on from here and access the files directly within the shiny app, for example, get all the uploaded data files into one data.frame to perform a loop later on.
for example we have
data_1 <- "data file 1"
data_2 <- "data file 2"
data_3 <- "data file 3"
data_4 <- "data file 4"
dataSet <- data.frame(DATA= c(1,2,3,4),
DATAFILE=c(data_1 ,data_2 ,data_3 ,data_4))
Is there any way to do that? I hope I have been able to explain myself thoroughly. I really appreciate any help you can provide.
library(shiny)
options(shiny.maxRequestSize = 30 * 1024^2)
ui <- fluidPage(
fileInput("upload", NULL, buttonLabel = "Upload...", multiple = TRUE),
tableOutput("files")
)
server <- function(input, output, session) {
output$files <- renderTable(input$upload)
}
shinyApp(ui, server)
input$upload is a data.frame containing four columns, to read the files we'll need datapath column that contains the temp path with the uploaded data, in this case they are csv's. From there we use a function like readr::read_csv() to transform the raw uploaded data into a df.
We can construct a reactive that consists in a list with all the uploaded files in it.
# read all the uploaded files
all_files <- reactive({
req(input$upload)
purrr::map(input$upload$datapath, read_csv) %>%
purrr::set_names(input$upload$name)
})
Full app:
library(shiny)
library(tidyverse)
library(DT)
# create some data to upload
write_csv(mtcars, "mtcars.csv")
write_csv(mpg, "mpg.csv")
write_csv(iris, "iris.csv")
options(shiny.maxRequestSize = 30 * 1024^2)
ui <- fluidPage(
fileInput("upload", NULL, buttonLabel = "Upload...", multiple = TRUE),
DT::DTOutput("files"),
tableOutput("selected_file_table")
)
server <- function(input, output, session) {
output$files <- DT::renderDT({
DT::datatable(input$upload, selection = c("single"))
})
# read all the uploaded files
all_files <- reactive({
req(input$upload)
purrr::map(input$upload$datapath, read_csv) %>%
purrr::set_names(input$upload$name)
})
#select a row in DT files and display the corresponding table
output$selected_file_table <- renderTable({
req(input$upload)
req(input$files_rows_selected)
all_files()[[
input$upload$name[[input$files_rows_selected]]
]]
})
}
shinyApp(ui, server)
There are two stages to this:
When you select a file what happens is that is gets copied into a temp directory. One of the values returned by the input is the location of the temp file, another is the original file name.
Once you have the file path you can use a function to read the data from that temp file.
The example at the bottom of this should be helpful (although your example needs a little bit more than this one because you have selected multiple files):
https://shiny.rstudio.com/reference/shiny/1.6.0/fileInput.html
I am new to shiny and trying to combine a couple features and having some trouble.
I want for the user to be able to select a CSV and then be presented with a random instance (in this case tweet) from that table. The following code worked when "tweetData" was a statically loaded csv using read_csv.
## function to return random row number from data set
getTweet <- function(){
tweetData[sample(nrow(tweetData), 1), ]
}
function(input, output, session) {
## set reactive values, get randomized tweet
appVals <- reactiveValues(
tweet = getTweet(),
ratings = data.frame(tweet = character(), screen_name = character(), rating = character())
)
I want to instead use a dynamically chosen csv for "tweetData", something like adding this??
csvName <- reactive(paste0('../folder_path/', input$file_name))
selectedData <- read.csv(csvName)
How can use reactively chosen csvs to fit into the structure of the first code chunk?
You might be looking for fileInput for giving user an option to upload a dataset.
This is a simple reproducible example -
library(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput("file1", "Choose CSV File"),
),
mainPanel(
tableOutput("contents")
)
)
)
server <- function(input, output) {
output$contents <- renderTable({
req(input$file1)
read.csv(input$file1$datapath)
})
}
shinyApp(ui, server)
I am trying to use the diffR function to accept two .R files to compare the differences in a shiny app. Where someone can upload two R files and then it will utilize diffR to output.
I can run my code locally where I define my file one and file two as directories locally and then I'll get a side by side output of the code to show the differences. It highlights differences and then adjustments can be made.
server <- function(input, output, session) {
output$contents <- renderPrint({
info_old <- input$old_file
if(is.null(info_old))
return(null)
df_old <- readLines(info_old$datapath)
df_old
})
output$new_contents <- renderPrint({
info_new <- input$new_file
if(is.null(info_new)){return()}
df_new <- readLines(info_new$datapath)
df_new
})
output$exdiff <- renderDiffr({
diffr(info_old(), info_new(), wordWrap = input$wordWrap,
before = "Original_File", after = "New File")
})
}
I know this simple where both the old_file and the new_file are generated side. This stack answer shows exactly what I am looking for:
In R, find whether two files differ
Where the diffr package is used. I just want the user to have the ability to upload the two R files so do the side by side comparison instead of defining file a and b globally.
You can use the datapath given by the uploaded files: input$files[[1, 'datapath']].
If you like, a small remark on your (good) attempt. The diffr() function demands the connection to the file not the content itself. I ran into the same trap as well. So if you remove the readLines() in your code you should be pretty close.
You might want to include a test, that the length of uploaded files is not smaller or greater than 2, to ensure the app doesnt crash if e.g. only one file is given.
Reproducible example:
write.csv2(
x = "diff same",
file = "test.csv"
)
write.csv2(
x = "diffhere same",
file = "test2.csv"
)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput(
inputId = "files",
label = "Choose CSV File",
multiple = TRUE,
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv")
)
),
mainPanel(
tableOutput("contents"),
diffrOutput("exdiff")
)
)
)
server <- function(input, output) {
output$exdiff <- renderDiffr({
req(input$files)
diffr(
file1 = input$files[[1, 'datapath']],
file2 = input$files[[2, 'datapath']],
wordWrap = TRUE,
before = "f1",
after = "f2"
)
})
}
shinyApp(ui, server)
Does anyone know how to read pajek file in shiny and then find the degree of each vertex and output it to CSV file in descending order?
Here's the Pajek file i want to import in and export the degree into CSV.
In R, i know how to code it normally like this:
#read the pajek file in igraph
reponetwork <- read.graph("network.net", format = "pajek")
#Inspect the data:
degree(reponetwork)
sort(degree(reponetwork), decreasing = TRUE)
But I'm not sure how to do it in Shiny:
Here's what I've done so far:
ui.R
shinyUI(fluidPage(
titlePanel("Finding most influential vertex in a network"),
sidebarLayout(
sidebarPanel(
fileInput("graph", label = h4("Pajek file")),
downloadButton('downloadData', 'Download')
),
mainPanel( tabsetPanel(type = "tabs",
tabPanel("Table", tableOutput("view"))
)
)
)
))
server.R
library(igraph)
options(shiny.maxRequestSize=100*1024^2)
shinyServer(
function(input, output) {
filedata <- reactive({
inFile = input$graph
if (!is.null(inFile))
data <<- read.graph(file=inFile$datapath, format="pajek")
})
output$view <- renderTable({
if(is.null(filedata())) {
return()
}
df <- filedata()
vorder <-sort(degree(df), decreasing=TRUE)
DF <- data.frame(ID=V(df)[vorder], degree=degree(df)[vorder])
})
output$downloadData <- downloadHandler(
filename = function() {
paste(input$graph, '.csv', sep='')
},
# This function should write data to a file given to it by
# the argument 'file'.
content = function(file) {
write.csv(DF, file)
}
)
})
I'm not sure how to take the file from filedata() method where it reads the graph, then take it's degree of the pajek file then output them in CSV file where highest degree is at the top and lowest at the bottom.
and the desired CSV file columns should have: 1. Vertex id 2. Degree of that vertex
I might be misreading your script, but I think you need to move all of your data ingestion and manipulation out of the shinyServer() section of your 'server.R' file to the space preceding it. Generally, the only stuff that goes in the shinyServer() slot is the code that renders the reactive elements in your app. All of the prep for those reactive elements should come before the call to shinyServer(). See this part of the Shiny tutorial for more info on the recommended structure of that 'server.R' script.
I am currently writing a shiny app which imports a dataset and displays a manipulated version. To work on the shiny methods I am currently working on a simplified version which displays the imported dataset. I currently assign the imported dataset to a reactive value, and then use the render table as follows:-
shinyServer(function(input, output) {
DATA<-reactive({
input$filein
})
output$Dataset <- renderTable({
DATA()
})
})
The interface then produces a table with the following columns:-
name, size, type, datapath.
What I had in mind was to call the datapath variable, and use read.csv to call it within the renderTable function. I tried using:-
DATA()$datapath
However that doesn't seem to produce any result. Are there any other ways to extract this data within Shiny? I contemplated using vector indices as you would using regular R code however I am unsure as to whether or not that'll work within Shiny.
Here is an example for files in the current working directory. The example file I used was a minimal csv file (see bottom). Please note however that this is indeed limited to files in your working directory. If you want other files to be loaded you will need to have a further component to specify the path (possibly in the selectInput).
library(shiny)
library(tools)
runApp(
list(
ui = pageWithSidebar(
headerPanel("File Info Test"),
sidebarPanel(
p("Demo Page."),
selectInput("filein", "Choose File", choices=c("test.csv"))
),
mainPanel(
tableOutput("myTableInfo"),
tableOutput("myTable")
)
),
server = function(input, output){
mydata <- reactive({
read.csv(input$filein)
})
file_info <- reactive({
validate(
need(!is.null(input$filein), "please select file"
)
)
name <- input$filein
size <- file.info(input$filein)[['size']]
type <- file_ext(input$filein)
datapath <- file_path_as_absolute(input$filein)
cbind(name, size, type, datapath)
})
output$myTableInfo <- renderTable({
file_info()
})
output$myTable <- renderTable({
mydata()
})
}
)
)
test.csv
X1,X2,X3
1,2,3
4,5,6