R Studio Shiny Server - $ operator is invalid when using SQL scripts - r

Anyone run in to his problem? I have a shiny app that uses SQL files to import data from MS SQL server using the RODBC package. I've narrowed down the problem to here in the server.R file:
ch <- odbcConnect(dsn = xxxxxx)
iQry <- readChar("LeaderDashInd.sql", file.info("LeaderDashInd.sql")$size, T)
oQry <- readChar("LeaderDashOrg.sql", file.info("LeaderDashOrg.sql")$size, T)
iDat <- sqlQuery(channel = ch, query = iQry, stringsAsFactors = F)
oDat <- sqlQuery(channel = ch, query = oQry, stringsAsFactors = F)
odbcClose(ch)
# PREPROCESSING --------------------------
cy <- max(iDat$CampYear)
The app stops at the last line above and gives... Error in iDat$CampYear : $ operator is invalid for atomic vectors. I know this chunk is the problem because when I have the same app run off imported csv files, it works.
A couple things to note:
This code runs first in the server.R file outside the shinyServer function.
The app runs fine when launched from my workstation through R Studio. It only stops working when run on our Shiny Server installation.
Shiny packages are up to date and shiny server is a recent install.
Any thoughts?

FYI... changing the SQL query to a stored procedure and then calling the stored procedure with RODBC::sqlQuery fixed the problem. The $ operator invalid error was coming up because the query was not running and returning an empty vector.
Still doesn't explain why the stand alone query using readChar doesn't work in Shiny Server but hey... its a fix.

Related

Roracle special characters on ShinyServer (Linux)

There seem to be plenty of similar issues and answers to them, yet so far haven't found a solution that would work for me.
Issue in short: special characters (scandic letters, ohm-symbol, Celcius degree-symbol, etc.) get all scrambled up when application is run on Linux Shiny server. Data shown on Shiny Dashboard is queried from Oracle database. The column name in these examples is "NAME" and type is VARCHAR2. When I run similar code on Linux server in R or on my local Windows RStudio, all characters look fine.
What I've tried so far: Characters started to look fine in Linux R after placing NLS_LANG to NLS_LANG=AMERICAN_AMERICA.AL32UTF8 in /etc/environment. I figured these are correct NLS_LANG settings by running SELECT * FROM V$NLS_PARAMETERS and SELECT * from NLS_SESSION_PARAMETERS in Linux's R. Though this didn't fix the issue on the Shiny Server side.
Also I've played around with the dbConnect encoding-parameter, with no luck.
Somewhat reproducible example: (sorry I can't gain access to my Oracle server ;-) )
library(ROracle)
ORAdrv <- dbDriver("Oracle", unicode_as_utf8 = TRUE, ora.attributes = TRUE) #doesn't matter if I have these two latter attributes or not
ORAconnect.string <- paste(
"(DESCRIPTION=",
"(ADDRESS=(PROTOCOL=tcp)(HOST=xx.xx.xx.xx)(PORT=xxxx))",
"(CONNECT_DATA=(SID=...)))", sep = ""
)
query2 <- ("select NAME, DATA_FIELD from TABLE where DATA_FIELD in ('ID7018789', 'ID7025838', 'ID7021380')")
ORAcon <- dbConnect(ORAdrv, username = "...", password = "...", dbname = ORAconnect.string, encoding = "UTF-8") #doesn't matter if encoding is defined or not
res <- dbSendQuery(ORAcon, query2, 'set character set "utf8"') #doesn't matter if the last attribute is defined or not
df <- fetch(res)
dbDisconnect(ORAcon)
print(df)
What the end result looks like:
If I run the code in Linux R, the result is what is expected (Ohm, Celcius symbols and scandic characters look good):
If I run the same code and render the dataframe as datatable on ShinyServer app, the result is like this: (Ohm and Celcius symbols are replaced with question mark, scandic characters รครถ -> ao)
Any help on getting the encoding correctly on Shiny Server application side is highly appreciated =)
I was able to solve it finally. If someone else is struggling with this, cast the column to nvarchar already in the query.
in my case, to_nchar(NAME) did the trick.
https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions187.htm

How to use shiny app as a target in drake

How to pass previous target (df) to ui and server functions that I use in the next command shinyApp. My plan looks like this:
plan <- drake_plan(
df = faithful,
app = shinyApp(ui, server)
)
ui and server are copied from the shiny tutorial. There's only one difference - I changed faithful to df (data in the previous target).
Now I'm getting an error:
Warning: Error in $: object of type 'closure' is not subsettable
[No stack trace available]
How to solve this? What's the best practice?
drake targets should return fixed data objects that can be stored with saveRDS() (or alternative kinds of files if you are using specialized formats). I recommend having a look at https://books.ropensci.org/drake/plans.html#how-to-choose-good-targets. There issues with defining a running instance of a Shiny app as a target.
As long as the app is running, make() will never finish.
It does not really make sense to save the return value of shinyApp() as a data object. That's not really what a target is for. The purpose of a target is to reproducibly cache the results of a long computation so you do not need to rerun it unless some upstream code or data change.
Instead, I think the purpose of the app target should be to deploy to a website like https://shinyapps.io. To make the app update when df changes, be sure to mention df as a symbol in a command so that drake's static code analyzer can pick it up. Also, use file_in() to declare your Shiny app scripts as dependencies so drake automatically redeploys the app when the code changes.
library(drake)
plan <- drake_plan(
df = faithful,
deployment = custom_deployment_function(file_in("app.R"), df)
)
custom_deployment_function <- function(file, ...) {
rsconnect::deployApp(
appFiles = file,
appName = "your_name",
forceUpdate = TRUE
)
}
Also, be sure to check the dependency graph so you know drake will run the correct targets in the correct order.
vis_drake_graph(plan)
In your previous plan, the command for the app did not mention the symbol df, so drake did not know it needed to run one before the other.
plan <- drake_plan(
df = faithful,
app = shinyApp(ui, server)
)
vis_drake_graph(plan)

RStudio Server - load file.RData Error : invalid multibyte string

I have a file file.RData with one of the data frames containing values with Swedish characters.
When loading file.RData in the Shiny app, it works fine on the local Windows machine, but when I move it to Ubuntu server and run it in RStudio Server: I get Error : invalid multibyte string
I changed Ubuntu's locale to sv_SE.UTF-8, rebooted and I still get the error. I've been looking at other similar problems link1 link2 , but don't know how to adapt it to my particular situation.
Is there any way to make my Shiny app work on Shiny server and keep file.RData with Swedish characters?
Here's a sample of my code in app.R:
library(shiny)
library(ggplot2)
library(lubridate)
(WD <- getwd())
if (!is.null(WD)) setwd(WD)
load ("file.RData")
server<-function(input,output){
.......
}
ui<-fluidPage(
.......
)
shinyApp(ui = ui, server = server)
I managed to convert the columns of the data frames, which had Swedish characters, by adding the following code after loading the file.RData:
load ("file.RData")
Encoding(df1$TEAM)<-"latin1"
Encoding(df2$TEAM)<-"latin1"
Encoding(df3$Team)<-"latin1"

Is there a way to paste csv data into R instead of reading from file?

I am currently trying to publish a shinyapp to shinyapp.io but I am having trouble configuring my rdrop2 token to upload my data file with it. It is in csv form and I using app.R. Since I cannot upload the token on here in fear of having my Dropbox completely available online I will do my best.
The function I am using with rdrop2 is the following:
token <- drop_auth()
saveRDS(token, "droptoken.rds")
token <- readRDS("droptoken.rds")
drop_acc(dtoken = token)
statadata <- drop_read_csv("/shinyapp/alldata.csv")
g <- na.omit(statadata)
data <- reactive({
g[1:input$scatterD3_nb,]
})
ui <- fluidPage(...
When I run the shiny app on RStudio it is fully functional but when I deploy the app it gives me one of two errors.
ERROR: oauth_listener() needs an interactive environment.
or
Error in func(fname, ...) : app.R did not return a shiny.appobj object.
neither error occurs when I am just printing it into the RStudio viewer.
While I fix this issue is there a way to simply create the data set by copying the csv file text editor version directly into r with something like
read.csv("country,nutsid,year,cyril_index_left,delta_cyril_left,manifesto,cyril_index_abs
,cyril_index,cyril_index_right,delta_cyril_right,Employment_15_64_,Employment_total,youth_employment,L_Employment_total,
L_youth_employment,growth, Austria,AT11,2002,-1017.925,-216.9429,-17.64,72.93657,1017.925,
0,-977.0339,1.1,0.9,0.5,-2.1,-8.9,4.7,Austria,AT11,2006,-923.9658,93.95892,
-4.308,104.4628,923.9658,0,0,0.8,0.4,-1.9,2.5,2.8,1.6", sep = ",")
I really do not see any other solution because shiny won't read my data from local files anyway.
You can use the text= argument to read.table (and therefore read.csv):
x <- read.csv(text="country,nutsid,year,cyril_index_left,delta_cyril_left,manifesto,cyril_index_abs,cyril_index,cyril_index_right,delta_cyril_right,Employment_15_64_,Employment_total,youth_employment,L_Employment_total,L_youth_employment,growth
Austria,AT11,2002,-1017.925,-216.9429,-17.64,72.93657,1017.925,0,-977.0339,1.1,0.9,0.5,-2.1,-8.9,4.7
Austria,AT11,2006,-923.9658,93.95892,-4.308,104.4628,923.9658,0,0,0.8,0.4,-1.9,2.5,2.8,1.6")
Sure. Use something like this.
Lines <- "
header1, header2
val1, 12
val2, 23
"
con <- textConnection(lines)
data <- read.csv(con)
close(con)
You can simplify and have the multiline expression around read.csv(textConnection("...here...")) as well.
You can also paste from the clipboard, but that tends to get OS specific and less portable.

Is it possible to run (execute) an r script from inside of an r script?

first time here and maybe I am out of place with this question, but I was unable to found an answer
I want to run a Shiny App with only one button, that runs an R script in order to generate a PPT file, something like what happens in this link, just instead of the MSWord output the PPT.
I want to avoid to have all the lines inside the ReporteRs-PPT_v3.R script inside the Shiny script and just call it or execute it like in any other lenguage.
I was trying something like this:
observe({
source("C:/Data/Example/Shiny/App-Ficha/ReporteRs-PPT_v3.R")
})
Also tried this other option:
observe({
R CMD BATCH /ReporteRs-PPT_v3.R
})
Where ReporteRs-PPT_v3.R is an existent script that by itself generates a PPT file using ReporteRs
Any idea on where can I keep looking?
Thanks.
[UPDATE]
The error when try the first option:
Listening on http://127.0.0.1:6158
Error in source(serverR, local = new.env(parent = globalenv()), keep.source = TRUE) :
C:\Data\Example\Shiny\App-Ficha/server.R:219:0: unexpected end of input
217: }
218: )
^
The error with the second option:
Listening on http://127.0.0.1:6158
Error in source(serverR, local = new.env(parent = globalenv()), keep.source = TRUE) :
C:\Data\Example\Shiny\App-Ficha/server.R:161:9: unexpected symbol
160: #source("C:/Data/Example/Shiny/App-Ficha/ReporteRs-PPT_v3.R")
161: R CMD
^
Also, when I click the button in the Shiny App, nothing happens.

Resources