Exercise 5 Statistical Programming

Exercise 1 — Convert temperatures

convert_temperature = function(celsius, target="Fahrenheit"){
  
  if(celsius < -273.15){
    stop("Temperature can't be colder than -273.15!")
  }
  
  if(target == "Kelvin"){
    return(paste(celsius+273.15,"K"))
  } else {
    return(paste(1.8*celsius+32,"°F"))
  }

}

convert_temperature(30)
[1] "86 °F"
convert_temperature(0,"Kelvin")
[1] "273.15 K"

Exercise 2 — Return score summaries in a list

summarize_practice = function(x){
  if(!is.numeric(x)){stop("Input must be number")}
  list( n=length(x),
        average=mean(x),
        median=median(x),
        minimum=min(x),
        maximum=max(x))
  
}
practice_scores <- c(78, 82, 90, 74, 86)
res = summarize_practice(practice_scores)
res
$n
[1] 5

$average
[1] 82

$median
[1] 82

$minimum
[1] 74

$maximum
[1] 90
res$average
[1] 82

Exercise 3 — Standardize values

standardize = function(x) {
  z = (x-mean(x))/sd(x)
  return(z)
}
practice_x <- c(55, 65, 70, 80, 90)

standardize(practice_x)
[1] -1.2583965 -0.5181632 -0.1480466  0.5921866  1.3324198

Exercise 4 — Find the median by hand

median_by_hand  = function(x){
  if(!is.numeric(x)){stop("Input must be number")}
  x = sort(x)
  n = length(x)
  if(n %% 2 == 0){
    m = x[n/2] + x[(n/2)+1]
    return(m/2)
    
  } else {
    return(x[(n+1)/2])
  }
}

practice_odd <- c(9, 2, 7, 4, 6)
practice_even <- c(9, 2, 7, 4)

median_by_hand(practice_odd)
[1] 6
median_by_hand(practice_even)
[1] 5.5

Exercise 5 — Find two tied modes

practice_modes <- c(1, 1, 3, 3, 3, 5, 5, 5, 8)

modes_by_hand = function(x){
  un = unique(x)

  freqNum = data.frame(
    num = un,
    freq = 0
  )
  
# Count the frequency for each number
  
  for(i in un){
    sum = 0
    for(j in x){
      if(j == i){
        sum = sum + 1
      }
    }
    freqNum[freqNum$num==i,2] = sum
  }

  max_f = max(freqNum[,2])
  return(
    list(
      modes = freqNum[freqNum$freq==max_f,1], 
      highestFrequency = max_f
      )
    )

}

modes_by_hand(practice_modes)
$modes
[1] 3 5

$highestFrequency
[1] 3