Digital Data Collection - programming extras

Rolf Fredheim and Yulia Shenderovich
University of Cambridge

24/02/2015

Variables

uni  <-  "The University of Cambridge"
uni
[1] "The University of Cambridge"

Paying tax:

#9400 tax free
(20000-9440)*20/100
[1] 2112
#OR:
wage <- 20000
taxFree <- 9400
rate <- 20
(wage-taxFree)*rate/100
[1] 2120

Briefly about functions

plusOne <- function(x){ 
    return(x+1)         
    }

plusOne2 <- function(num){ 
        return(num+1)           
    }

  • Curly brackets {} include the code to be executed
  • Normal brackets () contain a list of variables
    plusOne(8)
[1] 9
    plusOne2(10)
[1] 11
  plusOne2(num=5)
[1] 6
  #plusOne2(wrongVar=2)

part2

print(paste0("Percentage to go: ",round(as.numeric(daysLeft)/as.numeric(totDays)*100)))
[1] "Percentage to go: 13"
df <- data.frame(days=c(daysLeft,totDays-daysLeft),lab=c("to go","completed"))
ggplot(df,aes(1,days,fill=lab))+geom_bar(stat="identity",position="fill")

plot of chunk unnamed-chunk-18

We could put all this code in a function, and forget about it

timeToWorry <- function(){
  require(lubridate)
  deadline=as.Date("2015-09-01")
  daysLeft <- deadline-Sys.Date()
  totDays <- deadline-as.Date("2011-10-01")
  print(daysLeft)
  print(paste0("Rolf is struggling to finish his PhD on time. Days remaining: ", as.numeric(daysLeft)))
  print(paste0("Percentage to go: ",round(as.numeric(daysLeft)/as.numeric(totDays)*100)))
  df <- data.frame(days=c(daysLeft,totDays-daysLeft),lab=c("to go","completed"))
  ggplot(df,aes(1,days,fill=lab))+geom_bar(stat="identity",position="fill")
}

File it away until in need of a reminder

timeToWorry()
Time difference of 190 days
[1] "Rolf is struggling to finish his PhD on time. Days remaining: 190"
[1] "Percentage to go: 13"

plot of chunk unnamed-chunk-20