Skip to content

Instantly share code, notes, and snippets.

@tdhopper
Created August 30, 2014 13:56
Show Gist options
  • Save tdhopper/ce7720dafbd9881a6f58 to your computer and use it in GitHub Desktop.
Save tdhopper/ce7720dafbd9881a6f58 to your computer and use it in GitHub Desktop.
Smooth Weight from Text File Created by IFTTT
INPUT_PATH <- "~/Dropbox/Text Notes/Weight.txt"
OUTPUT_PATH <- "~/Dropbox/Text Notes/Weight Stats.txt"
library(lubridate)
library(ggplot2)
library(zoo)
# READ FILE
con <- file(INPUT_PATH, "rt")
lines <- readLines(con)
close(con)
# PARSE INTO LISTS OF WEIGHTS AND DATES
parse.line <- function(line) {
s <- strsplit(line, split=" ")[[1]]
date.str <- paste(s[2:10][!is.na(s[2:10])], collapse=" ")
date <- mdy_hm(date.str, quiet=TRUE)
l <- list(as.numeric(s[1]), date)
names(l) <- c("weight", "date")
l
}
list.weight.date <- lapply(lines, parse.line)
weights <- lapply(list.weight.date, function(X) X$weight)
dates <- lapply(list.weight.date, function(X) X$date)
# BUILD DATA FRAME
df <- data.frame(weight = unlist(weights), date = do.call("c", dates) )
# CREATE TIME SERIES AND RESAMPLE
ts <- zoo(c(df$weight), df$date)
ts <- aggregate(ts, time(ts), tail, 1)
g <- round(seq(start(ts), end(ts), 60 * 60 * 24), "days")
ts <- na.approx(ts, xout = g)
# FUNCTION TO GET WEIGHT N-DAYS AGO IF WEIGHT IS SMOOTHED BY ROLLING MEDIAN
# OVER A GIVEN (smooth.n) NUMBER OF DAYS
days.ago <- function(days, smooth.n) {
date <- head(tail(index(ts),days + 1),1)
smoothed <- rollmedianr(ts, smooth.n)
as.numeric(smoothed[date])
}
# SMOOTH WEIGHT BY 29 DAYS AND GENERATE SOME SUMMARY STATS
days = 29
current.weight <- days.ago(0, days)
x <- c(current.weight,
current.weight-days.ago(7, days),
current.weight-days.ago(30, days),
current.weight-days.ago(365, days),
current.weight-max(ts))
x = round(x, 1)
names(x) = c("current", "7days", "30days", "365days", "max")
fileConn<-file(OUTPUT_PATH)
w <- c(paste("Weight (lbs):", x["current"]),
paste("Total Δ:", x["max"]),
paste("1 Week Δ:", x["7days"]),
paste("1 Month Δ:", x["30days"]),
paste("1 Year Δ:", x["365days"]))
writeLines(w,fileConn)
close(fileConn)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment