Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting reactive data.frames in Shiny

Tags:

r

shiny

I have a working shiny application, but I am changing it so that the input data is reactive - it will update when the underlying data updates. It worked fine when it just read in the data, but now that the data is reactive I am having problems with one of the files (two others work just as expected). The file is a .csv which is exported from a database, and I would like to do a little housekeeping before using - change some names and format some data. The relevant part is:

server.r

 W.Data<-reactiveFileReader(2000,session,
          "WaterData.csv",read.csv,header=TRUE,as.is=TRUE)

This works fine, but then the next two lines won't work:

names(W.Data())[names(W.Data())=="Visit_Start_Date"]<-"Visit.Date" 
W.Data()$Visit.Date<-as.Date(W.Data()$Visit.Date,"%m/%d/%Y")   

When i run this I get

Error in W.Data()$VisitDate <- as.Date(W.Data()$VisitDate, "%m/%d/%Y"):
invalid (NULL) left side of assignment

and similar for the other line. What is going on here? Can I do these sort of things with a data.frame that is read from reactiveFileInput? I tried changing the names in the underlying .csv file to have underscores rather than spaces, and I tried putting the names() and as.Date() in reactive() expressions, but these made no difference.

Thanks

like image 322
John Paul Avatar asked Nov 25 '13 19:11

John Paul


1 Answers

I am responding to my own question largely to say that I was being a nincompoop. Once the file is read in using reactiveFileReader() it becomes a "reactive source". As explained in the shiny tutorial here the reactive sources are modified from outside - a user entering a new value, or in this case, an update of the file. You can't modify it from inside the server.r.

So, for my case I used the col.names and colClasses options in read.csv() to get the original data in the best format that I could. I also made use of the very useful setAs function to get read.csv to understand how to format the date, as explained here: Specify date format for colClasses argument ... .

From there, any new columns that I needed to create from the data had to be done as a separate object using a reactive function like this:

NewThing<-reactive({ function(MyReacitveCSVdata()$colname) })

And then NewThing() in turn can be used however you wish. This is how you can get around issues such as character values in an otherwise numeric column. If you try to just bring it in using colClasses="numeric" you will get an error and the read.csv() will fail. Instead first import the column as "character" and then use reactive({}) with as.numeric() to assign it to a new object. Be sure to note that the new object cannot be a new column in the data.frame you brought in using reactiveFileReader(), instead it must be a new object that depends on that data.frame.

like image 110
John Paul Avatar answered Nov 16 '22 23:11

John Paul