#####################
## Performance Tip ##
#####################

# Growing objects is usually bad

X <- rnorm(1000000)
Y <- rnorm(1000000)

system.time(X%*%Y)

vmult <- function(a,b){
  out <- 0.0
  for (i in 1:length(a)){
    out <- out + a[i]*b[i]
  }
  out
}

system.time(vmult(X,Y))


# Doing it inside double loops is especially bad

X <- matrix(rnorm(1000*1000), nrow = 1000)
Y <- matrix(rnorm(1000*1000), nrow = 1000)
system.time({M1 <- X %*% Y})
matmult <- function(A,B){
  out <- matrix(NA, nrow = nrow(A), ncol = ncol(B))
  for (i in 1:nrow(A)){
    for (j in 1:ncol(B)){
      out[i,j] <- vmult(A[i,], B[,j])
    }
  }
}

system.time({M2 <- matmult(X,Y)})
###############
## Functions ##
###############


## Dots arguments
f <- function(...){
  argList <- list(...)
  unnamed <- sum(names(argList) == "")
  cat(paste0(unnamed, " unnamed arguments.", "\n"))
  cat(paste0(length(argList) - unnamed, 
             " named arguments.", "\n"))
  for (n in names(argList)){
    if (n != "") cat(
      paste0("Argument ", n, " is: ", argList[[n]], "\n")
    )
  }
}

my_plot_function <- function(lmobj, ...){
  if (length(intersect(c("residuals", "fitted.values"), 
                       names(lmobj))) != 2){
    stop("Missing residuals or fitted values")
  }
  resids <- lmobj$residuals
  fitval <- lmobj$fitted.values
  plot(resids ~ fitval, ...)
}

lm.out <- lm(Sepal.Width ~ ., data = iris)
my_plot_function(lm.out, col = "green", main = "Title")



f(10, 20, rnorm(200), variable1 = 10, variable2 = "AAAAA")


####


a <- list(f,f,f)
b <- list(my_plot_function,my_plot_function,my_plot_function)
m <- cbind(a,b)
df <- as.data.frame(m)

# What are the formal arguments?
formals(my_plot_function)
# What does the function body look like?
body(my_plot_function)
# Where was the function declared?
environment(my_plot_function)
# What does the source code look like?
attr(my_plot_function, "srcref")
print(my_plot_function)


## Infix Functions

library(dplyr)
install.packages("dplyr")

select(iris, Sepal.Width) %>% summarize(meanWidth = mean(Sepal.Width))


`%+%` <- function(a,b){
  paste0(a,b)
}

"String1 " %+% "String2"


f <- function(c){
  return(c+2)
}

f(10)



##################
## Environments ##
##################

#########################
## Reference semantics ##
#########################

# Environments are sometimes compared to lists. Let's take 
# a look at how they differ. First, with lists:
myList <- list()

f <- function(env){
  env$variable <- 10
}

f(myList)
myList$variable


# Next, with an environment:
myEnv <- new.env(parent = emptyenv())

names(myEnv)
f(myEnv)
myEnv$variable

# We can copy the contents of one environment to another (question in class)
copy_contents <- function(env_input, env_output){
  for (nm in names(env_input)){
    env_output[[nm]] <- env_input[[nm]] 
  }
}

newEnv <- new.env(parent = emptyenv())
names(newEnv)

copy_contents(myEnv, newEnv)
names(newEnv)

# Some functions take environments as arguments
assign(x="some_global_variable", value = "yep, it's global",
       envir = globalenv())
some_global_variable

?environment
environment()

# Types of environments
myEnv$f <- f
environment(myEnv$f)

names(myEnv)
f
myEnv$f

# A recursive function listing its environments
f <- function(e){
  print("===========")
  print("Env:")
  print(environment())
  print("Parent Frame:")
  print(parent.frame())
  print("e:")
  print(e)
  Sys.sleep(5)
  f(environment())
}

f(environment())

## Enclosing vs. Binding environments:
A <- 10
f <- function(){
  print(A+2)
}

e <- new.env(parent = emptyenv())
e$f <- f
environment(e$f)
# f can still find A:
e$f()




