date format change with DT and shiny - r

my problem is when i use datatable on my computer and on the server formatDate is changing
i know i'm using method = 'toLocaleDateString' maybe it's not the good method
on my computer it give me the format i want :
1 février 2000
21 mars 2000
on shiny it give me :
01/02/2000
21/03/2000
local computer and server have Sys.timezone()
[1] "Europe/Paris"
im trying to do it like this
a <-structure(list(timestamp = structure(c(949363200, 953596800,
961286400, 962582400, 965347200, 969667200),
class = c("POSIXct", "POSIXt"), tzone = "UTC"),
anoms = c(1, 1, 1, 1, 1, 2), syndrome = c("Acrosyndrome",
"Acrosyndrome", "Acrosyndrome", "Acrosyndrome", "Acrosyndrome",
"Acrosyndrome")), .Names = c("timestamp", "anoms", "syndrome"
), row.names = c(NA, 6L), class = "data.frame")
datatable(a) %>% formatDate( 1, method = 'toLocaleDateString')
a
Thank you

With the development version of DT (>= 0.2.2) on Github, you can pass additional parameters to the date conversion method, e.g.
datatable(a) %>%
formatDate(1, method = 'toLocaleDateString', params = list('fr-FR'))
Or more parameters:
datatable(a) %>% formatDate(
1, method = 'toLocaleDateString',
params = list('fr-FR', list(year = 'numeric', month = 'long', day = 'numeric'))
)

Related

How to NOT write_csv if data frame is empty

I have a dataframe that is gathered everyday via a sql query. Sometimes it'll have rows in it, sometimes it wont. I then write_csv it into a onedrive location which triggers an automated email.
df and code like this if relevant:
df<-structure(list(PROTOCOL_ID = numeric(0), PROTOCOL_NO = character(0),
STATUS = character(0), STATUS_DATE = structure(numeric(0), tzone = "", class = c("POSIXct",
"POSIXt")), PROCESSED_FLAG = character(0), INITIATOR_CODE = numeric(0),
CHANGE_REASON_CODE = numeric(0), PR_STATUS_ID = numeric(0),
COMMENTS = character(0), CREATED_DATE = structure(numeric(0), tzone = "", class = c("POSIXct",
"POSIXt")), CREATED_USER = character(0), MODIFIED_DATE = structure(numeric(0), tzone = "", class = c("POSIXct",
"POSIXt")), MODIFIED_USER = character(0), OUTCOME_ID = numeric(0),
IRB_NO = character(0), NCT_NUMBER = character(0), PI_NAMES = character(0)), row.names = integer(0), class = "data.frame")
write_csv(df, "df.csv")
If the dataframe has zero rows that day, I'd rather it DIDN'T write the csv. I'm sure I could figure out a step that deletes the data frame if empty and then the write_csv line would error, but I'd rather not do that. Is there an easy way to 'turn off' the write?
We could have a condition to only write to csv when the number of rows is greater than 0
if(nrow(df) > 0) readr::write_csv(df, "df.csv")

How can I transform data from tidy to a unique format?

I have a dataset in which there are dates describing a time period of interest, as well as events ("Tests" in my toy example) that can fall inside or outside the period of the interest. The events also have a time and some dichotomous characteristics.
My collaborator has asked me to transform the data from this format:
structure(list(ID = c(1, 1, 2, 3), StartDate = structure(c(315878400,
315878400, 357696000, 323481600), class = c("POSIXct", "POSIXt"
), tzone = "UTC"), EndDate = structure(c(316137600, 316310400,
357955200, 323654400), class = c("POSIXct", "POSIXt"), tzone = "UTC"),
TestDateTime = structure(c(316135500, 315797700, 357923700,
323422560), class = c("POSIXct", "POSIXt"), tzone = "UTC"),
TestName = c("Test1", "Test2", "Test1", "Test3"), Characteristic = c("Fast",
"Slow", "Fast", "Slow")), row.names = c(NA, -4L), class = c("tbl_df",
"tbl", "data.frame"))
current state
to this format:
desired state
I am unsure how to accomplish this transformation or set of transformations using R, but I believe it is possible.
try the following
library(dplyr)
data %>%
select(-c(StartDate,EndDate)) %>% # Remove extra columns
tidyr::spread(TestDate, TestTime) %>% # Spread df to long form
select(-Characteristic, everything()) %>% # Move Characteristic to the end of the df
group_by(ID) %>% # Group by ID and
group_split() # split it
Take on count that the date columns of the final df are not exact as the "desire" state.
Hope this can help you.

Using literal month names with year in ramcharts

Here is my code to generate barplot using rAmChart,
library(rAmCharts)
amBarplot(x = "month", y = "value", data = dataset,
dataDateFormat = "MM/YYYY", minPeriod = "MM",
show_values = FALSE, labelRotation = -90, depth = 0.1)
However, is there a way to use month names & year in my x axis? I am trying to use MMM-YY formats.
Sample dataset,
structure(list(value = c(11544, 9588, 9411, 10365, 11154, 12688
), month = c("05/2012", "06/2012", "07/2012", "08/2012", "09/2012",
"10/2012")), .Names = c("value", "month"), row.names = c(NA,
6L), class = "data.frame")
Thanks.
It appears that rAmCharts doesn't expose AmCharts' dateFormats setting in the categoryAxis, so you have to access it through the init event and create your own dateFormats array with a modified format string for the MM period. I'm not very experienced with R, but here's how I managed to make it work using R 3.4.2 and rAmCharts 2.1.5
chart <- amBarplot( ... settings omitted ... )
addListener(.Object = chart,
name = 'init',
expression = paste(
"function(e) {",
"e.chart.categoryAxis.dateFormats = ",
'[{"period":"fff","format":"JJ:NN:SS"},{"period":"ss","format":"JJ:NN:SS"},',
'{"period":"mm","format":"JJ:NN"},{"period":"hh","format":"JJ:NN"},{"period":"DD","format":"MMM DD"},',
'{"period":"WW","format":"MMM DD"},',
'{"period":"MM","format":"MMM-YY"},', # "add YY to default MM format
'{"period":"YYYY","format":"YYYY"}]; ',
'e.chart.validateData();',
"}")
)
Here is a different solution:
library(rAmCharts)
dataset <- structure(list(value = c(11544, 9588, 9411, 10365, 11154, 12688
), month = c("05/2012", "06/2012", "07/2012", "08/2012", "09/2012",
"10/2012")), .Names = c("value", "month"), row.names = c(NA,
6L), class = "data.frame")
dataset$month <- as.character(
format(
as.Date(paste0("01/",dataset$month), "%d/%m/%Y"),
"%B %Y"))
amBarplot(x = "month", y = "value", data = dataset,
show_values = FALSE, labelRotation = -90, depth = 0.1)

Access First Graph

So I am using the PerformanceAnalytics package to plot performance summary of a simple PnL series so
library(xts)
library(PerformanceAnalytics)
dates <- structure(c(14008, 14011, 14012, 14013, 14014, 14015, 14018, 14019, 14020, 14021),
class = "Date")
PnL.xts = structure(c(0, -0.00510803851321091, -0.0102109843849305, -0.00138369232677364,
-0.00255257489213331, -0.00200279255353461, 0.0104232666033935,
0.00181846800788812, 4.72633257030091e-05, 0.0138334493571853),
.Dim = c(10L, 1L),
index = structure(c(1210291200, 1210550400, 1210636800, 1210723200,
1210809600, 1210896000, 1211155200, 1211241600,
1211328000, 1211414400),
tzone = "UTC", tclass = "Date"),
.indexCLASS = "Date", tclass = "Date",
.indexTZ = "UTC", tzone = "UTC", .Dimnames = list(NULL, "PnL"),
class = c("xts", "zoo"))
PnL.cum = cumsum(PnL.xts)
ret.ann = Return.annualized(PnL.xts, geometric = FALSE)
ret.cum = Return.cumulative(PnL.xts, geometric = FALSE)
ret.min = min(PnL.cum)
stdev = StdDev.annualized(PnL.xts)
sharpe = SharpeRatio.annualized(PnL.xts, geometric = FALSE)
stats = paste(paste("Annualized Return:", percent(round(ret.ann, 5))),
paste("Cumulative Return:", percent(round(ret.cum, 5))),
paste("Standard Deviation:", round(stdev, 5)),
paste("Sharpe Ratio:", round(sharpe, 5)), sep = '\n' )
lag = 1
descr = paste("Following fitted Granger model - ", lag, " day lag", sep = "")
charts.PerformanceSummary(R = PnL.xts, geometric = FALSE)
text(midrange(dates),ret.min, labels = stats, cex = 1)
mtext(descr, side = 3, line = 31)
However, I want to add some descriptive text into the cumulative PnL chart such as annualized return, cumulative return, standard deviation, and sharpe. How can I paste this into the whitespace in the first graph?
If I plotted the graph by itself, I could just do it with the above code. However, since the charts.PerformanceSummary function automatically plots 3 graphs, I can only access the 3rd graph it seems. Is there any way to access the first of 3 graphs printed by a function, so that I can write text on it relative to its own coordinates?
Here is an example of what I want: http://i.imgur.com/QXUb2Aq.png. But in this case, I had to manually, test values of the y coordinate until I found somthing that worked. Thanks!

R crashes while using data.table

sac[,treatment_days := as.character(seq(from = SACDPDAT, to = SACRTDAT, by = "1 day")), by = PACKID] I have data named sac with dput(sac[1:2,]) as follows:
structure(list(SUBJECT_Blinded = c(1201001, 1101001), LINE = c(8,
4), MODULE = c("SAC", "SAC"), CENTRE_Blinded = c(1201, 1201),
STUDYPER = c(7, 4), PACKID = c(10096, 10595), SACDPDAT = structure(c(1335304800,
1325545200), class = c("POSIXct", "POSIXt"), tzone = ""),
SACDP1 = c(35, 35), C_SACDP = c(NA_character_, NA_character_
), SACRTDAT = structure(c(1340316000, 1327964400), class = c("POSIXct",
"POSIXt"), tzone = ""), SACRT1 = c(0, 9), C_SACRT = c(NA_character_,
NA_character_)), .Names = c("SUBJECT_Blinded", "LINE", "MODULE",
"CENTRE_Blinded", "STUDYPER", "PACKID", "SACDPDAT", "SACDP1",
"C_SACDP", "SACRTDAT", "SACRT1", "C_SACRT"), sorted = c("SUBJECT_Blinded",
"PACKID"), class = c("data.table", "data.frame"), row.names = c(NA,
-2L))
When I running the code:
sac[,treatment_days := list(format(seq(from = SACDPDAT, to = SACRTDAT, by = "1 day"),"%Y-%m-%d")), by = PACKID]
RStudio crushes and returns info:
Problem signature:
Problem Event Name: APPCRASH
Application Name: rsession.exe
Application Version: 0.98.501.0
Application Timestamp: 52e8371d
Fault Module Name: R.dll
Fault Module Version: 3.3.65126.0
Fault Module Timestamp: 53185fd3
Exception Code: c0000005
Exception Offset: 0000000000028c36
OS Version: 6.1.7601.2.1.0.256.48
Locale ID: 1045
Additional Information 1: 4fc0
Additional Information 2: 4fc0e6e5b53a870c89fb6e37a38d7e6b
Additional Information 3: 9d6e
Additional Information 4: 9d6e8f79167930945e5a5d06afac680e
It's the same with pure R. Any ideas how to do it another way?
There's a couple of problems with your new code:
"1 day" is incorrect, if you run seq on a date object, the number you pass to by will be interpreted as days, so:
seq(from = SACDPDAT, to = SACRTDAT, by = 1)
You also cannot create a new column from this sequence, because there can only be one value for each row. Instead, you can generate the sequence of days by PACKID, and then join this onto the old data.table
So try:
setkey(sac, PACKID)
sac <- sac[sac[,seq(from = SACDPDAT, to = SACRTDAT, by = 1), by=PACKID]]

Resources