Skip to content

Instantly share code, notes, and snippets.

@guychouk
Last active May 7, 2024 17:50
Show Gist options
  • Save guychouk/dc6f12f7c84ed5ad4c8ec1d774fe5067 to your computer and use it in GitHub Desktop.
Save guychouk/dc6f12f7c84ed5ad4c8ec1d774fe5067 to your computer and use it in GitHub Desktop.
๐Ÿ’ธ Analyzing my finances CSV with R
# function that reverses a string by characters
reverse_chars <- function(string)
{
# split string by characters
string_split = strsplit(string, split = "")
# reverse order
rev_order = nchar(string):1
# reversed characters
reversed_chars = string_split[[1]][rev_order]
# collapse reversed characters
paste(reversed_chars, collapse = "")
}
# read a csv into a list
finances2018 <- read.csv('./finances-2018.csv')
# create a table from two data columns in the dataset.
# by default, this gives the number of times each value appeared.
table(finances2018$ืงื˜ื’ื•ืจื™ื”, finances2018$ืกื›ื•ื.ืฉื—ื•ื™ื™ื‘)
# replace the shekel sign with nothing in the ืกื›ื•ื.ืฉื—ื•ื™ื™ื‘
# column.
gsub("โ‚ช", "", finances2018$ืกื›ื•ื.ืฉื—ื•ื™ื™ื‘)
# parse the ืกื›ื•ื.ืฉื—ื•ื™ื™ื‘ as numeric
as.numeric(gsub("โ‚ช", "", finances2018$ืกื›ื•ื.ืฉื—ื•ื™ื™ื‘))
# generate two new lists:
# amounts list as numbers and a categories list matching each value.
amounts <- as.numeric(gsub(",", "", gsub("โ‚ช", "", finances2018$ืกื›ื•ื.ืฉื—ื•ื™ื™ื‘)))
# apply function to each value in list, similar to map()
categories <- sapply(finances2018$ืงื˜ื’ื•ืจื™ื”, reverse_chars)
# these two then get converted via an aggregate
amountByGroup <- aggregate(x=list(Amounts=amounts), by=list(Categories=categories), FUN=sum)
# create a pie chart from the
png(file = "spendings.png")
pie(amountByGroup$Amounts, amountByGroup$Categories)
dev.off()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment