Data Programming

Homework 3

Author

Mirko Dugajlic

Published

May 7, 2024

Libraries

library(tidyverse)
library(ggplot2)

Plots

# make proper time for beaver1
month <- as.Date(beaver1$day, origin = "1990-1-1")
hour <- beaver1$time %/% 100
minutes <- beaver1$time %% 100
beaver1$date <- ymd_hm(paste(month, sprintf("%02d:%02d", hour, minutes)))


# make proper time for beaver2
month <- as.Date(beaver2$day, origin = "1990-1-1")
hour <- beaver2$time %/% 100
minutes <- beaver2$time %% 100
beaver2$date <- ymd_hm(paste(month, sprintf("%02d:%02d", hour, minutes)))

beaver1$data.frame <- "beaver1"
beaver2$data.frame <- "beaver2"

# merge data frames
dataframe_to_display <- bind_rows(beaver1,beaver2) 

ggplot(dataframe_to_display, aes(x=date, y = temp, color = data.frame)) +
  geom_line() +
  facet_wrap(~data.frame, scales = "free_x") + 
  labs(title = "Temperature of beavers over time",
       x = "",
       y = "Temperature (\u00B0C)") +
  theme(legend.position="right") 

Second task

convert.all <- function(currency_vector, convert_currency="EUR"){
  # Currency to convert doesn't exist
  if (!(convert_currency %in% names(euro)) && convert_currency!="EUR") {
    return(0)
  }
  
  # If there exists more than one amount with same currency
  currency_amount <- tapply(currency_vector, names(currency_vector), sum)

  # Calculate total in EUR and after that convert if defined
  total_eur <- sum(sapply(names(currency_amount), function(valute) {
  if (!(valute %in% names(euro)) && valute != "EUR") {
    return(0)
  }
  amount <- currency_amount[valute]
  if (valute != "EUR") {
    amount / euro[valute]
  } else {
    amount
  }
}))

# Convert to target currency if needed
if (convert_currency != "EUR") {
  total_eur <- total_eur * euro[convert_currency]
}

# Set the name dynamically
result <- total_eur
names(result) <- NULL

return(result)
}


convert.all(c(EUR=6.5))
[1] 6.5
convert.all(c(EUR=3,ATS=2))
[1] 3.145346
convert.all(c(EUR=3,EUR=2))
[1] 5
convert.all(c(EUR=3,DEM=2,SIT=10000))
[1] 4.022584
convert.all(c(EUR=3,DEM=2,SIT=10000),"EUR")
[1] 4.022584
convert.all(c(EUR=3,SIT=10000,DEM=2),"ESP")
[1] 669.3016
convert.all(c(EUR=3,DEM=2,LIRA=100),"SIT")
[1] 0