-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot.total.R
More file actions
71 lines (58 loc) · 2.48 KB
/
plot.total.R
File metadata and controls
71 lines (58 loc) · 2.48 KB
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
#Sum of expenses per category in the period
plot.total <- function(f.date.start = today(), #As "%Y %m %d"
f.date.stop = today(), #As "%Y %m %d"
f.numofcat = NULL)
{
##Coherce f.dates as a Date class object ----
f.date.start <- ymd(f.date.start)
f.date.stop <- ymd(f.date.stop)
##Input Error -----
if (f.date.stop < f.date.start) {
stop("Stop date prior to Start date. Please correct")
}
#define the dates -------------
#start date
day(f.date.start) <- 1#Define the initial start date to search
#stop date
day(f.date.stop) <- 1
month(f.date.stop) <-month(f.date.stop) + 1
day(f.date.stop) <-day(f.date.stop) - 1#point it to monthend
#ORGANIZE THE FILE----------------
#load data
load("totalcostsdata.rda")
tempframe <- data
#turn negative amounts in positive
tempframe$amount <- abs(as.numeric(tempframe$amount))
#Transform the date column in a date vector
tempframe$date <- as.Date(tempframe$date)
#create the specific tempframe for the answer
tempframe <- tempframe[tempframe$date >= f.date.start,]
#adjusting levels of tempframe
tempframe$category <-
droplevels.data.frame(tempframe)$category
#define the number of f.numofcat
if (is.null(f.numofcat)) {
f.numofcat <- length(levels(tempframe$category))
}
#The vector of amounts to be printed ----
amounts.to.print <- sort(tapply(tempframe$amount,
tempframe$category,
sum),
decreasing = T)[1:f.numofcat]
####Return of error --------------------
if (nrow(tempframe) == 0) {
stop("No information in the selected period")
}
#print the plot ------------------
theplot <- barplot(amounts.to.print,
names.arg = names(amounts.to.print),
col=1:length(levels(tempframe$category)),
ylab="Dollars",
xlab="Category",
main = "total spent by category")
legend("topright",
legend = c(
paste("Start ", f.date.start),
paste("Stop ", f.date.stop)))
return(data.frame(total=amounts.to.print))
}