Question 1

The following function satisfies the conditions listed below:

  1. Only takes a vector as an input.
  2. Returns basic summary statistics, if the input is a numeric vector.
  3. Returns a frequency table, if the input is a character vector.
# Creating test variables
x <- c(12, 20, 18, 32, 15, 20) # Numeric
y <- c("M", "M", "F", "F", "M", "M", "M", "F") # Character

# Creating aforementioned function
SummaryStat <-  function(x){
  if (class(x) == "numeric") {
    Summ <-  summary(x)
    StandardDev <-  sd(x)
    Summary <- c(Summ, "Std.Dev." = StandardDev) 
    return(Summary)
  } else {
    Tab <- table(x)
    return(Tab)
  }
}

# Testing function with test variables
SummaryStat(x)
##      Min.   1st Qu.    Median      Mean   3rd Qu.      Max.  Std.Dev. 
## 12.000000 15.750000 19.000000 19.500000 20.000000 32.000000  6.862944
SummaryStat(y)
## x
## F M 
## 3 5

Question 2

The following function satisfies the conditions listed below:

  1. Only takes a character vector as input.
  2. Returns a character vector as such that each element of it only has the first letter capitalized.
# Character vector that we will use to test our function
Names1 <- names(mtcars)
Names1
##  [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear"
## [11] "carb"
# Creating the function
UpperCase1 <- function(x) {
  if(class(x) == "character"){
    Fl <- toupper(substr(x, 1, 1))
    Word <- tolower(substr(x, 2, nchar(x)))
    paste0(Fl, Word, collapse = NULL)
  } else {
    print("Only applicable to character vectors.")
  }
}

# Testing the function on the test vector
UpperCase1(Names1)
##  [1] "Mpg"  "Cyl"  "Disp" "Hp"   "Drat" "Wt"   "Qsec" "Vs"   "Am"   "Gear"
## [11] "Carb"