Shiny manipulating input$df with reactive - r

I am new to shiny and trying to modify this code to allow for the function to be used from a dynamically selected csv.
## function to return random row number from data set
getTweet <- function(){
tweetData[sample(nrow(tweetData), 1), ]
}
our_tweet <- isolate(appVals$tweet)
output$tweet <- renderText({ our_tweet$tweet })
output$screen_name <- renderText({ our_quote$screen_name })
output$resultsTable <- renderDataTable({appVals$ratings})
The above code works when tweetData is a static csv read in through read.csv() but when I try to use a drop down to select csv the only way I am able to run without error is putting it inside of a renderDataTable() function. How could I use reactive values within input$file and still be able to run the above code.
Code using renderDataTable():
output$test <- renderDataTable({
req(input$file)
csvName <- paste0('../path/to/file/', input$file)
selectedData <- read.csv(csvName)
selectedData
})
I want to be able to do something like this:
csvName <- paste0('../path/to/file/', input$file)
selectedData <- read.csv(csvName)
selectedData[sample(nrow(selectedData), 1), ]

You could create reactive functions:
csvName <- reactive(paste0('../path/to/file/', input$file))
selectedData <- reactive(read.csv(csvName()))
You can then use the reactive functions in other reactives like renderDataTable:
output$test <- renderDataTable({
selectedData()[sample(nrow(selectedData()), 1), ]
})
Don't forget the () when calling the result of reactive functions : csvName(), selectedData(), , ...

Related

Rename Colnames from dataframe

I am making a Shiny App and I would like to rename the first variable from dataframe, to make after a corrplot.
In normal R the code is:
library(lares)
names(Dataset)[1] <- "DR"
corr_var(Dataset, DR, top=20)
And in Shiny I have something:
dataReg2 = reactive({
inFile <- input$fileReg
if (is.null(inFile))
return(NULL)
else
data1 = read_excel(inFile$datapath)
return(data1)
})
plot=reactive({
names(dataReg2())[[1]]='DR'
corr_var(dataReg2(), DR , top = 20 )
})
But it doesn't work, the error is invalid (NULL) left side of assignment...
Thank you in advance.
You cannot change the column names of reactive object. Copy the data in another variable and you can change the column name of that variable. See this simple example using mtcars.
library(shiny)
ui <- fluidPage(
tableOutput('tab')
)
server <- function(input, output) {
data <- reactive(mtcars)
output$tab <- renderTable({
new_table <- data()
names(new_table)[1] <- 'new'
head(new_table)
})
}
shinyApp(ui, server)

How to save data in database from shiny app?

I want to save user'S data in the db.
Every user's data should be submitted per row without any error. The data is in a function with if else condition. Every if else's output is to be saved against it's user. How can I do it?
I tried creating a dataframe for it but still the data wasn't saved in it.
Here is reprex of my code.
library(shiny)
library(tidyverse)
ui <- fluidPage(
textInput("my_in","type a value for an entry"),
actionButton("newline_but","press for a new entry"),
tableOutput("showmytable")
)
server <- function(input, output, session) {
mydf <- reactiveVal(tibble(msg=NA_character_))
output$showmytable <- renderTable({
mydf()
})
observeEvent(input$my_in,{
local_df <- req(mydf())
curr_row <- nrow(local_df)
local_df[curr_row,1] <- input$my_in
mydf(local_df)
})
observeEvent(input$newline_but,{
local_df <- req(mydf())
mydf(add_row(local_df))
})
observeEvent(mydf(),
{
#export to a global but would be better to maybe write to a database
assign(x="exported_df",
value=mydf(),
envir = .GlobalEnv)
})
}
shinyApp(ui,server)```

Using Shiny to update dataframe values and access it in the local environment after Shiny session ends

I have been going through most of the Q&As related to dataframe manipulation within Shiny and I still don't understand how to do something which, in my mind, should be very simple. I don't have experience writing Shiny apps and I'm still struggling with concepts like reactive events.
I have a dataframe A, loaded into R. I want to be able to see a specific value in a specific column in the dataframe in the UI and then edit it. After I edit the dataframe, I want to close the Shiny app and then see the edited dataframe in the Environment tab of RStudio. How do I go about doing this?
I think this might be a workable example.
Assume df is your data frame (I used iris to test, commented out below). Create a reactiveVal to hold your data, and use for editing with datatable. After editing, you can store the data back into your global environment dataframe df with <<-. An alternative is to do this when exiting the shiny app (such as through the onStop or session$onSessionEnded method).
library(shiny)
library(DT)
#df <- iris
ui <- fluidPage(
DT::dataTableOutput('data'),
)
server <- function(input, output) {
rv <- reactiveVal(df)
output$data <- DT::renderDataTable ({
DT::datatable(rv(), editable = TRUE)
})
observeEvent(input$data_cell_edit, {
info <- input$data_cell_edit
newdf <- rv()
newdf[info$row, info$col] <- info$value
rv(newdf)
df <<- rv()
})
}
shinyApp(ui = ui, server = server)
Alternative with replacing global df on exiting (requires session):
server <- function(input, output, session) {
rv <- reactiveVal(df)
output$data <- DT::renderDataTable ({
DT::datatable(rv(), editable = TRUE)
})
observeEvent(input$data_cell_edit, {
info <- input$data_cell_edit
newdf <- rv()
newdf[info$row, info$col] <- info$value
rv(newdf)
})
session$onSessionEnded(function() {
df <<- isolate(rv())
})
}
If you don't want to use reactive values, I suppose you could try the following. This can update your data.frame in the global environment as edits are made. Note that server = FALSE is added to handle changes in pages:
server <- function(input, output) {
output$data <- DT::renderDT (df, editable = TRUE, server = FALSE)
observeEvent(input$data_cell_edit, {
info <- input$data_cell_edit
df[info$row, info$col] <<- info$value
})
}

Accessing data in different parts of server() in shiny

I am having a problem with accessing data in different parts of my server() function. The basic structure is something like this:
server <- shinyServer(function(input, output) {
# get the data from a file obtained from a textInput in the ui
data <- reactive({
req(input$file)
file <- input$file$datapath
# process the file and return a new dataframe
})
output$head <- renderTable({
mydf <- data()
head(mydf)
})
output$tail <- renderTable({
mydf <- data()
tail(mydf)
})
})
I would like to avoid having to call data() twice but I haven't found a way to do that.
Edit following the comment by #KentJohnson
What I am trying to achieve is for the user to select a file to open, using textInput, and after the file is opened, the app should do some processing and populate the two tables in the ui. After this, the user then chooses some other actions which also require the same data.
I wanted to avoid having to call data() twice but I haven't found a way to do that. I was assuming that each call would mean reading from the file each time. The file is very large so that is my motivation.
As #KentJohnson points out, reactive already achieves your goal. The expression that makes up data...
req(input$file)
file <- input$file$datapath
# process the file and return a new dataframe
...only runs when input$file$datapath changes. It does not rerun each time data() is called.
Putting your two tables into an observe environment makes it possible to call data() only twice, but I don't know if it will fit with what you want to do. Notice that here, I didn't put a textInput or things like that because my point was to show the observe environment. I'll let you adapt it to your situation (since you didn't put the ui part in your post):
library(shiny)
ui <- basicPage(
fileInput("file",
"Import a CSV file",
accept = ".csv"),
tableOutput("head"),
tableOutput("tail")
)
server <- shinyServer(function(input, output) {
# get the data from a file obtained from a textInput in the ui
data <- reactive({
req(input$file)
inFile <- input$file
read.csv(inFile$datapath, header = F, sep = ";")
# process the file and return a new dataframe
})
observe({
mydf <- data()
if (is.null(mydf)){
output$head <- renderTable({})
output$tail <- renderTable({})
}
else {
output$head <- renderTable({
head(mydf)
})
output$tail <- renderTable({
tail(mydf)
})
}
})
})
shinyApp(ui, server)
Edit: I misunderstood the OP's question, see #SmokeyShakers' answer for a more appropriate answer.

failed to display variable data types in shiny flexdashboard

I am trying to display variable types dynamically and my code is something like this (using into flexdashboard shiny app):
tblCls <- reactive({
req(input$file1)
inFile <- input$file1
if (is.null(inFile)){
return(NULL)
}else{
datatable(head(read.csv(inFile$datapath, header = input$header), 5))
}
})
output$class <- renderText({
print(class( tblCls() ))
})
textOutput("class")
I read the csv file from fileInput method.
The result is expected something what we get when do str(DF) in R but what I am getting is datatables htmlwidget as output.
Not sure what I have done wrong here, need to understand the correct method.
Here's what you need -
tblCls <- reactive({
req(input$file1) # if else not needed when using req()
head(read.csv(input$file1$datapath, header = input$header), 5)
})
output$class <- renderPrint({
str(tblCls())
})
textOutput("class")

Resources