forked from statwonk/openfda-dashboard
-
Notifications
You must be signed in to change notification settings - Fork 6
/
data.R
120 lines (107 loc) · 3.05 KB
/
data.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
query_drug <- function(drug) {
fda_query("/drug/event.json") %>%
fda_filter("patient.drug.openfda.generic_name",
drug)
}
count_fda <- function(variable, ...) {
dots <- unlist(list(...))
validate(
need(length(dots) <= 6,
message = "Only up to six drugs allowed for now!"),
errorClass = "too-many-warning"
)
do.call(rbind,
lapply(dots, FUN = function(input_drug) {
tryCatch(
tbl_df(
query_drug(input_drug) %>%
fda_count(variable) %>%
fda_exec()
) %>%
mutate(drug = input_drug),
error = function(e) {
stop("Oops, something went wrong!")
})
}))
}
dates_received <- reactive({
if(is.null(input$drug))
return()
isolate({
d <- count_fda(variable = "receivedate",
input$drug)
d <- d %>%
mutate(time = as.POSIXct(time,
format = "%Y%m%d"))
# One possible extention is to add a grouping
# toggle like: month, week, day
d <- d %>%
mutate(time = cut.POSIXt(time, 'week',
start.on.monday = F)) %>%
group_by(drug, time) %>%
summarise(count = sum(count)) %>%
mutate(time = as.character(time),
time = as.POSIXct(time))
# There are trade-offs in terms of counting weeks
# without adverse events as 0 or NA.
# Splines work in log-scale if weeks without events
# are set to NA. In general, counting 0s are
# important for distributional modeling and even smoothing.
# For many drugs 0 counts are rare in given weeks.
# date_sequence <- data.frame(
# time = as.POSIXct(
# seq(min(d$time),
# max(d$time),
# by = "week"),
# format = "%Y-%m-%d"))
#
# d <- left_join(date_sequence,
# d) %>%
# mutate(count = ifelse(is.na(count), 0, count))
return(d)
})
})
ages <- reactive({
if(is.null(input$drug))
return()
isolate({
count_fda(variable = "patient.patientonsetage",
input$drug) %>%
filter(term < 120)
})
})
outcomes <- reactive({
if(is.null(input$drug))
return()
isolate({
as.data.frame(
tbl_df(
dcast(
count_fda(variable = "patient.reaction.reactionoutcome",
input$drug),
term ~ drug,
value.var = "count"
)
) %>%
mutate(term = sapply(term, function(x) {
switch(x,
"Recovered/resolved",
"Recovering/resolving",
"Not recovered/not resolved",
"Recovered/resolved with sequelae",
"Fatal",
"Unknown")})) %>%
rename(Outcome = term)
)
})
})
reactionoutcomes <- reactive({
if(is.null(input$drug))
return()
isolate({
dcast(
count_fda(variable = "patient.reaction.reactionmeddrapt.exact",
input$drug),
term ~ drug, value.var = "count")
})
})