Go back to Index

Functions

  1. Create a function that takes a vector c(1,2,3,4,5) and returns a vector conatining the mean, the sum, the standard deviation and the median
f1 <-function(v){
  r1 = mean(v)
  r2 =sum(v)
  r3=sd(v)
  r4=median(v)
  return(c(r1,r2,r3,r4))
}

f1(c(1,2,3,4,5))
  1. Modify your function to return a list instead of a vector
f1.1 <-function(v){
  r1 = mean(v)
  r2 =sum(v)
  r3=sd(v)
  r4=median(v)
  return(list(r1,r2,r3,r4))
}

f1.1(c(1,2,3,4,5))
  1. Create a function that recieves the matrix D defined above. The result should be the sum of the diagonal of the inner product.
f2 <- function(D){
  r1 = D%*%D
  r2 = diag(r1)
  return(sum(r2))
}

D <- matrix(c(10,20,30,40), nrow=2,ncol=2)

## Same thing
f2 <- function(D){
  return(sum(diag(D%*%D)))
}
  1. Create a function that receives an input of integers and returns a logical vector that is TRUE when the input is even and FALSE when is odd. HINT: Remember that %% is the operator for the remainder of a division
f3 <- function(v){
  r1 = v%%2
  return(r1==0)
}

f3(c(2,1,3,4))