Setup Inicial

knitr::opts_chunk$set(echo = TRUE)

setwd("C:/Users/victo/Desktop/R/e12/") # Current working directory

library(dplyr)
library(stringr)
library(tidyr)
library(plotly)

1)

MRT_1F <-c(517.1468515630205, 85.13094142168089, 30.333207896694553, 12.694776264558937, 3.3041601673945418, 1.1823111717498882, 1.1892293502386786)

MRT_3F <-c(156.68929936163462, 11.540837783562276, 0.4512835621696538, 0.4509797929766453, 0.4502068233039181, 0.4496185276300172, 0.4543157082191288)

MRT_5F <-c(83.90319666471157, 0.3068151086494968, 0.30522314133037304, 0.3072588968084928, 0.30655265997285697, 0.3055812715727718, 0.3053297166713006)

MRT_10F <-c(29.55430642951759, 0.19832832665772515, 0.1971923924717474, 0.19796648905716516, 0.19615594370806338, 0.2034569237883263, 0.19617420889447737)

MRT_15F <-c(11.317736530583566, 0.167364215666193, 0.16172168266811013, 0.16701085329580515, 0.1598052657153692, 0.1645934043532696, 0.16216563797118075)

MRT_sem_F <-c(11.93430909937736, 0.6095414637034009, 0.6060645101029295, 0.612167181646899, 0.6146761002685637, 0.6096747087200697, 0.6125810476877268)

clock <- c(0.1, 0.5, 1, 1.5, 2, 2.5, 3)

datasets <- matrix(c(MRT_1F, MRT_3F, MRT_5F, MRT_10F, MRT_15F, MRT_sem_F), nrow=6, byrow=T)
colors <- c("black", "yellow", "red", "blue", "purple", "green")
pchs <- c(4,15,1,2,5,4)
legends <- c("1 Fog", "3 Fogs", "5 Fogs", "10 Fogs", "15 Fogs", "w/o Fog")

plot(clock, MRT_1F, type="n", pch=NA, xlab="Time between Things Request (seconds)", ylab="Response Time (sec.)")
for (i in 1:length(colors)) {
  lines(clock, datasets[i, ], type="o", pch=pchs[i], col=colors[i])
}
legend(x="topright", legend=legends,col=colors, pch=pchs, lty=c(1,1,1,1,1,1))

plot_bar <- function(ds, second_legend) {
  barplot(
    height = rbind(MRT_sem_F, ds),
    log = "y",
    beside = TRUE,
    col = c("#E6E6E6", "#666666"),
    names.arg = clock,
    legend.text = c("w/o Fog", second_legend),
    args.legend = list(x = "topright"),
    xlab = "Time Between Things requests",
    ylab = "Response Time (s)"
  )
}

par(mfrow = c(3, 2), mar = c(4, 4, 4, 4), oma = c(0, 0, 0, 0))
plot_bar(datasets[1, ], legends[1])
plot_bar(datasets[2, ], legends[2])
plot_bar(datasets[3, ], legends[3])
plot_bar(datasets[4, ], legends[4])
plot_bar(datasets[5, ], legends[5])
par(mfrow = c(1, 1)) # Reset plot layout

2)

quality_rating <- c("Good", "Very Good", "Excellent")
faixas <- c("$10-19", "$20-29", "$30-39", "$40-49")
values <- matrix(c(53.8, 33.9, 2.6, 
                   0.0, 43.6, 54.2, 
                   60.5, 21.4, 2.6, 
                   11.9, 36.8, 78.6), nrow=3, byrow=T)
colors <- c("red", "green", "blue")
  
barplot(values,
        main = "Qualidade por Preços",
        names.arg = faixas,
        xlab = "Preço",
        ylab = "Quantidade (%)",
        # yaxt = "n",
        col = colors
)
legend(x="topright", title="Qualidade", title.col="black",
       legend=quality_rating,col=colors, text.col=colors)

3)

convert_to_celsius <- function(fahrenheit) {
  celsius <- (fahrenheit - 32) * 5/9
  return(celsius)
}

temperatures_celsius <- convert_to_celsius(
  airquality$Temp[airquality$Month == 5]
)

hist(temperatures_celsius, 
     main = "Histograma das temperaturas de maio (airquality)", 
     xlab =  "Temperaturas (ºC)",
     ylab = "Densidade",
     probability = T,
     col = "gray"
)
lines(density(temperatures_celsius))

4)

sales <- read.table(
  "https://training-course-material.com/images/8/8f/Sales.txt", header=TRUE
)

proportion <- round(sales$SALES / sum(sales$SALES) * 100)
colors <- rainbow(length(sales$COUNTRY))

pie(sales$SALES, 
    paste(sales$COUNTRY, paste(proportion, "%", sep="")),
    main = "Proporção de vendas dos paises",
    col = colors
)
legend(x="topright",legend=sales$COUNTRY,text.col=colors,title="Paises",title.col="black")

5)

boxplot(InsectSprays$count ~ InsectSprays$spray,
        main = "Distribuição da quantidade de sprays de cada tipo",
        xlab = "Tipos de spray",
        ylab = "Distribuição",
        outline = F,
        col="yellow",
)

6)

filenames <- c("monitoringCloudData_NONE.csv", 
               "monitoringCloudData_0.1.csv", 
               "monitoringCloudData_0.5.csv", 
               "monitoringCloudData_1.csv")
titles <- c("Memory Analysis (None Workload)", 
            "Memory Analysis (Workload of 0.1)",
            "Memory Analysis (Workload of 0.5)",
            "Memory Analysis (Workload of 1.0)")

convert_GB_to_MB <- function(memory_string) {
  
  # Captura 2 informações: o número e a unidade
  match <- regexec("([0-9.]+)([A-Za-z]+)", memory_string)

  if (length(match[[1]]) > 1) {
    # Extract numeric value and unit
    numeric_value <- as.numeric(regmatches(memory_string, match)[[1]][2])
    unit <- regmatches(memory_string, match)[[1]][3]

    # Convert to MB
    if (tolower(unit) == "gb") {
      return(numeric_value * 1024)
    } else if (tolower(unit) == "mb") {
      return(numeric_value)
    }
  }
  return(NA)
}

calculate_continuous_time <- function(df) {
  # Converte currentTime em tempo contínuo
  x_len <- length(df$currentTime)
  max_time <- difftime(df$currentTime[x_len], df$currentTime[1], units="hours")
  max_time <- as.numeric(max_time) 
  step <- max_time / x_len
  continuous_time_hours <- seq(0, max_time-step, by = step)
  return(continuous_time_hours)
}
  
# Main loop
par(mfrow=c(2,2), mar = c(3.9,4,3.9,4), oma = c(0,0,0,0)) # Define layout dos plots
for (i in 1:length(filenames)) {
  
  # Read csv
  df <- read.csv(
    filenames[i], 
    sep = ",", 
    strip.white = TRUE, 
    na.strings = "",
    header = TRUE
  )
  
  # Converte GB para MB
  df$usedMemoryNum <- sapply(df$usedMemory, convert_GB_to_MB)
  
  # Calcula o tempo contínuo (eixo horizontal)
  continuous_time_hours <- calculate_continuous_time(df)
  
  min_h <- round(min(df$usedMemoryNum))
  max_h <- round(max(df$usedMemoryNum))
  plot(continuous_time_hours, 
       df$usedMemoryNum, 
       type="l", pch=NA,
       main = titles[i],
       xlab="Time (hour)", 
       ylab="Used Memory (MiB)",
       ylim= c(min_h, max_h),
  )
  axis(1, at = seq(0, max(continuous_time_hours), by = 10), 
       labels = seq(0,max(continuous_time_hours), by = 10))
}

par(mfrow=c(1,1)) # Reseta layout

7)

df <- read.csv(
    "netflix_titles.csv", 
    sep = ",", 
    strip.white = TRUE, 
    na.strings = "",
    header = TRUE,
  fileEncoding = "UTF-8"
)

# Remove NA, linhas com múltiplos países e calcula os 10 paises com mais linhas
df_filtered <- df %>% 
  filter(!is.na(country)) %>%
  filter(str_count(country, ",") == 0) # Filtra linhas com apenas 1 pais
country_counts <- df_filtered %>% count(country, sort = TRUE)
top_countries <- head(country_counts, 10)

plot_ly(
  labels = top_countries$country,
  values = top_countries$n,
  type = "pie",
  textinfo = "percent+label",
  insidetextorientation = "radial"
) %>% 
  layout(
    title = "Top 10 Países com Mais Conteúdo na Netflix",
    margin = list(b = 100)
  )

8)

df <- read.csv(
    "netflix_titles.csv", 
    sep = ",", 
    strip.white = TRUE, 
    na.strings = "",
    header = TRUE,
  fileEncoding = "UTF-8"
)

# Remove NA, linhas com múltiplos países e calcula os 10 paises com mais linhas
df_filtered <- df %>% 
  filter(!is.na(country)) %>%
  filter(str_count(country, ",") == 0) # Filtra linhas com apenas 1 pais
country_counts <- df_filtered %>% count(country, sort = TRUE)
top_countries <- head(country_counts, 10)

plot_ly(
  type= 'table',
  columnwidth = c(50, 50),
  columnorder = c(0, 1),
  header = list(
    values = c("País", "Total de conteúdos"),
    align = c("center", "center"),
    line = list(width= 1.5, color = 'black'),
    font=list(family="Arial",size= 12, color = c("white")),
    fill = list(color = 'gray')
  ),
  cells = list(
    values = rbind(top_countries$country, top_countries$n),
    align = c("center", "center"),
    line = list(width= 1.5, color = 'black'),
    font=list(family="Arial",size= 12, color = c("white")),
    fill = list(color = 'gray')
  )
) %>% 
  layout(title = "Top 10 Países com Mais Conteúdo na Netflix")

9)

df <- read.csv(
    "netflix_titles.csv", 
    sep = ",", 
    strip.white = TRUE, 
    na.strings = "",
    header = TRUE,
  fileEncoding = "UTF-8"
)

# Convertendo a coluna release_year para décadas
df$decade <- as.factor((df$release_year %/% 10) * 10)

# Contando o número de títulos por década e tipo
count_by_decade <- df %>%
  group_by(decade, type) %>%
  summarise(count = n())

# Filtrando apenas séries e filmes
count_series <- count_by_decade %>%
  filter(type == "TV Show")
count_movies <- count_by_decade %>%
  filter(type == "Movie")

# Criando o gráfico de linha com pontos
plot <- plot_ly(type = "scatter")

# Adicionando a linha para séries (azul)
plot <- add_trace(
  plot,
  x = count_series$decade,
  y = count_series$count,
  mode = "lines+markers",
  name = "Séries",
  line = list(color = "blue"),
  marker = list(color = "blue")
)

# Adicionando a linha para filmes (amarelo)
plot <- add_trace(
  plot,
  x = count_movies$decade,
  y = count_movies$count,
  mode = "lines+markers",
  name = "Filmes",
  line = list(color = "orange"),
  marker = list(color = "orange")
)

# Personalizando o layout
plot <- layout(
  plot,
  xaxis = list(title = "Década"),
  yaxis = list(title = "Qnd. Conteúdo")
)

plot

10)

df <- read.csv(
    "netflix_titles.csv", 
    sep = ",", 
    strip.white = TRUE, 
    na.strings = "",
    header = TRUE,
  fileEncoding = "UTF-8"
)

df_filtered <- df %>%
  filter(
    !is.na(release_year),
    release_year > 2000,
    release_year < 2010,
    type == "Movie"
  )

order <- c("Dramas", "Action & Adventure", "Comedies")
order_pt_br <- c("Drama", "Ação e Aventura", "Comédia")
colors <- c("blue", "orange", "green")

# Extrair o primeiro gênero da lista
df_filtered$genre <- sub(",.*", "", df_filtered$listed_in)

# Contagem por ano e gênero
count_by_genre <- df_filtered %>%
  group_by(release_year, genre) %>%
  summarise(count = n())

# Filtrar apenas os gêneros desejados
count_by_genre_filtered <- count_by_genre %>% filter(genre %in% order)


plot <- plot_ly(type = "bar")

for (i in 1:length(order)) {
  plot <- add_trace(
    plot,
    x = count_by_genre_filtered$release_year[count_by_genre_filtered$genre == order[i]],
    y = count_by_genre_filtered$count[count_by_genre_filtered$genre == order[i]],
    type = "bar",
    name = order_pt_br[i],
    marker = list(color = colors[i]),
    position = "dodge"
  )
}

plot <- layout(
  plot,
  # title = "Quantidade de Filmes por Gênero (2000-2010)",
  xaxis = list(title = "Ano de Lançamento"),
  yaxis = list(title = "Qnt. de Lançamentos")
)

plot