using server.r side data in R functions outside of shiny

333 views
Skip to first unread message

David York

unread,
Jan 19, 2016, 6:37:46 PM1/19/16
to Shiny - Web Framework for R
I have been all over in an embarrassingly disorganized search to find out how to get shiny server data (specifically from a questionnaire interface) from UI.R passed to server.r as input) to be accessible by R code inorder to write is to a file on server-side. I have tried to avoid php in myhtml (very rusty there) to do this.

I found some rather terse stuff on stachoverflow which seemed what I wanted but I couldn't decypher it enough to get it to work.

"The answer is to define a variable outside of the shinyServer function. Then make a global assignment in the reactive functions by using <<- instead of <- or =. Then you have access to it outside of the reactive functions. However, You only have access to it while the application is running, but this isn't a problem for emailing yourself the input or writing the input to a text file." (R shiny: how to save input data to the server or access input variables globally?)

Anyway I couldn't get it to work. Also I looked at Joe Chen's suggestion about Leaflet but it was 3 years only and Leaflet changed to much to follow the suggestion.

What I have done is collect data in a survey, UI.R client and sent to server.R where I processed it a bit with feedback to respondant. All this works fine.

Now I want to take to survey response variables, concatinate to a CSV strin and write the line to a text (file as a CSV) I also tried to populate a dataframe with the data but shiny doesn't seem to talk back to R very well.

Any suggestions?

Dave

Just Learning shiny,
FYI, my most recent code . . .

ui.R:

library(shiny)
initialize global variable (outside shiny)
demog = NULL

shinyUI(fluidPage(

headerPanel(h2("Life Stress Survey", style="text-align:center")),

column(4,
h2("Instructions", style="text-align:center"),
p('If a life event has occurred for you, select "Yes". Otherwise check "No" or leave unchecked.'),
p('When the survey has been completed press "Submit and your score will be calculated and the score and its interpretation with respect to your 2 year illness risk will be returned.'),
#collectData<-Sys.Date(),
p("For the purposes of future follow-up an email is requested. In 1 and 2 years an email form will be sent to you with 2 simple outcome questions."),
textInput(inputId="subjEmail", label="Your email address", value = NULL, width = '200px'),

p("To apply the data by age, we request your age range. "),
selectInput(inputId="ageRange", "Age range now:",
c("under 18" = "17",
"18 to 25" = "20",
"26 to 35" = "30",
"36 to 45" = "40",
"46 to 55" = "50",
"56 to 64" = "60",
"over 65" = "65"), width="100px"),

p("To relate the data to a region of the US we request your ZIP code, which is not stored, but converted for storage to a US Census Tract number representing a whole block of ZIP codes."),
textInput(inputId="zipCode", label="ZIP Code", value="01001", width = "100px"),
br(),
p(strong("Thank you for contributing to this project."))
, style="background-color:Gold"),

column(8,
h2("Life Events Questions", style="text-align:center"),
column(6,
radioButtons(inputId="question1", label= "Death of Spouse", choices=c("No"=0, "Yes"=100), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question2", label="Divorce", choices=c("No"=0, "Yes"=73), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question3", label="Marital separation", choices=c("No"=0, "Yes"=65), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question4", label="Jail term", choices=c("No"=0, "Yes"=63), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question5", label="Death of close family member", choices=c("No"=0, "Yes"=63), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question6", label="Marriage", choices=c("No"=0, "Yes"=53), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question7", label="Fired at work", choices=c("No"=0, "Yes"=50), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question8", label="Marital reconciliation", choices=c("No"=0, "Yes"=47), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question9", label="Retirement", choices=c("No"=0, "Yes"=45), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question10", label="Change in health of family member", choices=c("No"=0, "Yes"=44), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question11", label="Pregnancy", choices=c("No"=0, "Yes"=40), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question12", label="Sex difficulties", choices=c("No"=0, "Yes"=39), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question13", label="Gain of new family member", choices=c("No"=0, "Yes"=39), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question14", label="Business readjustment", choices=c("No"=0, "Yes"=39), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question15", "Change in financial state", choices=c("No"=0, "Yes"=38), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question16", label="Death of close friend", choices=c("No"=0, "Yes=37"), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question17", label="Change to a different line of work", choices=c("No"=0, "Yes"=36), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question18", label="Change in number of arguments with spouse", choices=c("No"=0, "Yes"=35), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question19", label="Home Mortgage over $100,000", choices=c("No"=0, "Yes"=31), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question20", label="Foreclosure or mortgage or loan", choices=c("No"=0, "Yes"=30), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question21", label="Change in responsibilities at work", choices=c("No"=0, "Yes"=29), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question22", label="Son or daughter leaving home", choices=c("No"=0, "Yes"=29), selected = 0, inline = TRUE, width = NULL)
),

column(6,

radioButtons(inputId="question23", label="Trouble with in-laws", choices=c("No"=0, "Yes"=29), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question24", label="Outstanding personal achievement", choices=c("No"=0, "Yes"=28), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question25", label="Spouse begins or stops work", choices=c("No"=0, "Yes"=26), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question26", label="Begin or end school", choices=c("No"=0, "Yes"=26), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question27", label="Change in living conditions", choices=c("No"=0, "Yes"=25), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question28", label="Revision of personal habits", choices=c("No"=0, "Yes"=24), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question29", label="Trouble with boss", choices=c("No"=0, "Yes"=23), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question30", label="Change in work hours or conditions", choices=c("No"=0, "Yes"=20), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question31", label="Change in residence", choices=c("No"=0, "Yes"=20), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question32", label="Change in schools", choices=c("No"=0, "Yes"=20), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question33", label="Change in recreation", choices=c("No"=0, "Yes"=19), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question34", label="Change in church activities", choices=c("No"=0, "Yes"=19), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question35", label="Change in social activities", choices=c("No"=0, "Yes"=18), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question36", label="Mortgage or loan of less than $100,000", choices=c("No"=0, "Yes"=17), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question37", label="Change in sleeping habits", choices=c("No"=0, "Yes"=16), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question38", label="Change in number of family get-togethers", choices=c("No"=0, "Yes"=15), selected = 0, inline = TRUE, width = NULL),
radioButtons(inputId="question39", label="Change in eating habits", choices=c("No"=0, "Yes"=15), selected = 0, inline = TRUE, width = NULL),
sliderInput(inputId="question40", label="Single person living alone, Estimate the stress involved for yourself", min=0, max=15, value=0, step = NULL, round = TRUE, ticks = TRUE, animate = TRUE, width = NULL, sep = ",", pre = NULL, post = NULL, timeFormat = NULL, timezone = NULL, dragRange = TRUE),
sliderInput(inputId="question41", label="Other, describe briefly and estimate the stress involved for yourself", min=0, max=15, value=0, step = NULL, round = TRUE, ticks = TRUE, animate = TRUE, width = NULL, sep = ",", pre = NULL, post = NULL, timeFormat = NULL, timezone = NULL, dragRange = TRUE),
textInput(inputId="text41", label="Name stressor (up to 15 characters)", value = "", width = NULL)
),
br(),
span(submitButton("Submit Survey"), style="text-align:center"),
br()
,style="background-color:LemonChiffon"),

fluidRow(

    div(
h2("Interpretation"),
p("NOTE: Interpretation of the overall score is difficult because of the large differences in each person's ability to cope and their particular reactions to stress, but here are some general guidelines."),
p("A total of 150 or less is good, suggesting a low level of stress in your life and a low probability of developing a stress-related disorder."),

p("Your stress score is"),
textOutput("resultText0"),
textOutput("message"),
br(),

p("If your score is 300 or more, statistically you stand an almost 80% chance of getting sick in the near future. "),
p("If your score is 150 to 299, the chances are about 50%."),
p("At less than 150, about 30%."),
verbatimTextOutput("codedResponses"),
demog <<- verbatimTextOutput("studySumRec")

,style="padding:20px")
, style="background-color:Gold")

))

server.R:

library(shiny)

#initialized variables outside shiny server.R (to use to hold a record (files 2 records)
responses <- NULL
respondant <- NULL
varRspdt <- c("refNo", "collectDate","eMail", "cenTract", "ageGroup", "score")



shinyServer(
function(input, output) {

# next step convert this  to use an array
score <- reactive({sum(as.numeric(input$question1), as.numeric(input$question2), as.numeric(input$question3), as.numeric(input$question4), as.numeric(input$question5), as.numeric(input$question6), as.numeric(input$question7), as.numeric(input$question8), as.numeric(input$question9), as.numeric(input$question10), as.numeric(input$question11), as.numeric(input$question12), as.numeric(input$question13), as.numeric(input$question14), as.numeric(input$question15), as.numeric(input$question16), as.numeric(input$question17), as.numeric(input$question18), as.numeric(input$question19), as.numeric(input$question20), as.numeric(input$question21), as.numeric(input$question22), as.numeric(input$question23), as.numeric(input$question24), as.numeric(input$question25), as.numeric(input$question26), as.numeric(input$question27), as.numeric(input$question28), as.numeric(input$question29), as.numeric(input$question30), as.numeric(input$question31), as.numeric(input$question32), as.numeric(input$question33), as.numeric(input$question34), as.numeric(input$question35), as.numeric(input$question36), as.numeric(input$question37), as.numeric(input$question38), as.numeric(input$question39), as.numeric(input$question40), as.numeric(input$question41), as.numeric(input$question42))})

########

# create "blinded" reference number for record
refNo = "8999999999" # temporary demo dummy reference number

# create datestamp for collectDate
collectDate =
strftime(Sys.Date())

# convert ZIP to Census Tract
cenTract = reactive({input$zipCode})

# keep responses without identifiers send back to ui and store to files
output$codedResponses<-reactive({paste(c(refNo,input$question1,input$question2,input$question3,input$question4,input$question5,input$question6,input$question7,input$question8,input$question9,input$question10,input$question11,input$question12,input$question13,input$question14,input$question15,input$question16,input$question17,input$question18,input$question19,input$question20,input$question21,input$question22,input$question23,input$question24,input$question25,input$question26,input$question27,input$question28,input$question29,input$question30,input$question31,input$question32,input$question33,input$question34,input$question35,input$question36,input$question37,input$question38,input$question39,input$question40,input$question41,input$question42), sep=",")})

output$studySumRec <- reactive({paste(c(refNo, collectDate,input$subjEmail,cenTract(),input$ageRange,score()), sep=",")})

sink("text.txt", append=TRUE)     ## tried this, didn't work!
print(demog)                       # variable initialized outside shinyUI, has a printable value but is HTML tag only
sink()

#send back score to responder
output$resultText0 <- renderText(score())
}
)



Jian Wang

unread,
Jan 20, 2016, 11:40:38 PM1/20/16
to Shiny - Web Framework for R
David:

Two blogs by Dean Attali at http://deanattali.com/ should help to achieve your objectives.

Good luck.

-Jian
...

Dean Attali

unread,
Jan 21, 2016, 1:11:36 AM1/21/16
to Shiny - Web Framework for R
Yes, I haven't read your entire code, but it sounds like you're just trying to create a survey and save the data to a CSV file on the server.  Jian is right, those two blog posts are exactly what you're looking for. Thank you Jian

Austin T

unread,
Jan 22, 2016, 3:15:58 AM1/22/16
to Shiny - Web Framework for R
Why not use cat() or write()? Don't those work too?
...

Dean Attali

unread,
Jan 22, 2016, 3:19:48 AM1/22/16
to Shiny - Web Framework for R
Austin, do you mean using cat or write instead of write.csv? Sure, you could in theory.... but the responses to a survey make a nice dataframe , so why not use the most suitable function for writing a dataframe to file, which is write.csv?

David York

unread,
Jan 24, 2016, 11:55:18 AM1/24/16
to Shiny - Web Framework for R
Thanks Jian and Dean. I did find the articles mentioned and they helped alot. It was actually what I needed for the project and to understand the bigger picture (shiny issues of scope and variable visibility) better.

David
Reply all
Reply to author
Forward
0 new messages