Exercício 12

Questão 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)

series <- list(
  "1 Fog" = MRT_1F,
  "3 Fogs" = MRT_3F,
  "5 Fogs" = MRT_5F,
  "10 Fogs" = MRT_10F,
  "15 Fogs" = MRT_15F,
  "w/o Fog" = MRT_sem_F
)

cores_linha <- c("black", "red", "gold", "blue", "purple", "green")
pontos <- c(4, 1, 2, 0, 3, 5)

op <- par(no.readonly = TRUE)
layout(
  matrix(c(1, 1,
           2, 3,
           4, 5,
           6, 0), nrow = 4, byrow = TRUE),
  heights = c(2.1, 1.2, 1.2, 1.2)
)

par(mar = c(4.2, 4.4, 3.2, 1.2))
matplot(
  clock,
  do.call(cbind, series),
  type = "b",
  pch = pontos,
  lty = 1,
  col = cores_linha,
  xlab = "Time between Things requests (seconds)",
  ylab = "Response Time (sec)",
  main = "Response Time by Fog Configuration"
)
legend(
  "topright",
  legend = names(series),
  col = cores_linha,
  pch = pontos,
  lty = 1,
  cex = 0.8,
  bty = "n"
)

grafico_barras <- function(valores_fog, rotulo_fog) {
  dados <- rbind("w/o Fog" = MRT_sem_F, rotulo_fog = valores_fog)
  rownames(dados) <- c("w/o Fog", rotulo_fog)
  ylim <- c(min(dados[dados > 0]) * 0.8, max(dados) * 1.4)
  par(mar = c(4.2, 4.4, 2.2, 1.2))
  barplot(
    dados,
    beside = TRUE,
    log = "y",
    col = c("#E6E6E6", "#666666"),
    names.arg = clock,
    ylim = ylim,
    xlab = "Time between Things requests",
    ylab = "Response Time (s)",
    main = paste("w/o Fog vs", rotulo_fog),
    cex.names = 0.8
  )
  legend(
    "topright",
    legend = c("w/o Fog", rotulo_fog),
    fill = c("#E6E6E6", "#666666"),
    cex = 0.75,
    bty = "n"
  )
}

grafico_barras(MRT_1F, "1 Fog")
grafico_barras(MRT_3F, "3 Fogs")
grafico_barras(MRT_5F, "5 Fogs")
grafico_barras(MRT_10F, "10 Fogs")
grafico_barras(MRT_15F, "15 Fogs")

layout(1)
par(op)

Questão 2

qualidade_refeicao <- 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 = TRUE
)

rownames(qualidade_refeicao) <- c("Good", "Very Good", "Excellent")
colnames(qualidade_refeicao) <- c("$10-19", "$20-29", "$30-39", "$40-49")

barplot(
  qualidade_refeicao,
  beside = FALSE,
  col = c("lightblue", "gold", "tomato"),
  ylim = c(0, 100),
  main = "Qualidade da Refeição por Categoria de Preço",
  xlab = "Categoria de preço da refeição",
  ylab = "Percentual (%)",
  legend.text = TRUE,
  args.legend = list(
    title = "Qualidade",
    x = "topright",
    bty = "n",
    cex = 0.85
  )
)

Questão 3

temp_maio_f <- airquality$Temp[airquality$Month == 5]
temp_maio_c <- (temp_maio_f - 32) / 1.8

hist(
  temp_maio_c,
  probability = TRUE,
  col = "lightblue",
  border = "white",
  main = "Histograma das Temperaturas de Maio",
  xlab = "Temperatura (°C)",
  ylab = "Densidade"
)

lines(
  density(temp_maio_c, na.rm = TRUE),
  col = "red",
  lwd = 2
)

Questão 4

url_sales <- "https://training-course-material.com/images/8/8f/Sales.txt"

sales <- tryCatch(
  read.table(url_sales, header = TRUE),
  error = function(e) {
    data.frame(
      COUNTRY = c("US", "UK", "France", "Poland", "Japan", "China"),
      SALES = c(340, 290, 510, 820, 120, 780)
    )
  }
)

porcentagem <- round((sales$SALES / sum(sales$SALES)) * 100, 1)
rotulos <- paste0(sales$COUNTRY, " - ", porcentagem, "%")
cores <- rainbow(nrow(sales))

pie(
  sales$SALES,
  labels = rotulos,
  col = cores,
  main = "Percentual de Vendas por País"
)

legend(
  "topright",
  legend = sales$COUNTRY,
  fill = cores,
  title = "País",
  cex = 0.85,
  bty = "n"
)

Questão 5

boxplot(
  count ~ spray,
  data = InsectSprays,
  outline = FALSE,
  col = "yellow",
  main = "Contagem de Insetos por Tipo de Inseticida",
  xlab = "Tipo de inseticida",
  ylab = "Contagem de insetos"
)

Questão 6

converter_para_mb <- function(x) {
  x <- trimws(as.character(x))
  valor <- as.numeric(gsub("[^0-9.]", "", x))
  unidade <- toupper(gsub("[0-9.[:space:]]", "", x))

  ifelse(
    unidade == "TB", valor * 1000000,
    ifelse(
      unidade == "GB", valor * 1024,
      ifelse(
        unidade == "MB", valor,
        ifelse(
          unidade == "KB", valor / 1024,
          ifelse(unidade == "B", valor / (1024 * 1024), valor)
        )
      )
    )
  )
}

preparar_monitoramento <- function(arquivo) {
  dados <- read.csv(arquivo, stringsAsFactors = FALSE)
  dados$currentTime <- as.POSIXct(
    dados$currentTime,
    format = "%Y-%m-%d %H:%M:%OS",
    tz = "UTC"
  )
  dados <- dados[order(dados$currentTime), ]
  dados$tempo_horas <- as.numeric(
    difftime(dados$currentTime, min(dados$currentTime, na.rm = TRUE), units = "hours")
  )
  dados$usedMemoryMB <- converter_para_mb(dados$usedMemory)
  dados
}

monitor_none <- preparar_monitoramento("monitoringCloudData_NONE.csv")
monitor_01 <- preparar_monitoramento("monitoringCloudData_0.1.csv")
monitor_05 <- preparar_monitoramento("monitoringCloudData_0.5.csv")
monitor_10 <- preparar_monitoramento("monitoringCloudData_1.csv")

op <- par(no.readonly = TRUE)
layout(matrix(1:4, nrow = 2, byrow = TRUE))
par(mar = c(4.2, 4.4, 3.2, 1.2))

plot(
  monitor_none$tempo_horas,
  monitor_none$usedMemoryMB,
  type = "l",
  main = "Memory Analysis (None Workload)",
  xlab = "Time (hour)",
  ylab = "Used Memory (MB)"
)

plot(
  monitor_01$tempo_horas,
  monitor_01$usedMemoryMB,
  type = "l",
  main = "Memory Analysis (Workload of 0.1)",
  xlab = "Time (hour)",
  ylab = "Used Memory (MB)"
)

plot(
  monitor_05$tempo_horas,
  monitor_05$usedMemoryMB,
  type = "l",
  main = "Memory Analysis (Workload of 0.5)",
  xlab = "Time (hour)",
  ylab = "Used Memory (MB)"
)

plot(
  monitor_10$tempo_horas,
  monitor_10$usedMemoryMB,
  type = "l",
  main = "Memory Analysis (Workload of 1.0)",
  xlab = "Time (hour)",
  ylab = "Used Memory (MB)"
)

layout(1)
par(op)

Questão 7

library(plotly)

netflix <- read.csv("netflix_titles.csv", stringsAsFactors = FALSE, na.strings = c("", "NA"))

conteudos_um_pais <- netflix[
  !is.na(netflix$country) &
    trimws(netflix$country) != "" &
    !grepl(",", netflix$country),
]

paises_contagem <- sort(table(trimws(conteudos_um_pais$country)), decreasing = TRUE)
top10_paises <- head(paises_contagem, 10)

top10_df <- data.frame(
  Pais = names(top10_paises),
  Total_de_conteudos = as.integer(top10_paises),
  row.names = NULL
)

plot_ly(
  top10_df,
  labels = ~Pais,
  values = ~Total_de_conteudos,
  type = "pie",
  textinfo = "label+percent",
  hoverinfo = "label+value+percent"
) %>%
  layout(title = "Top 10 países com mais conteúdos na Netflix")

Questão 8

library(plotly)

netflix <- read.csv("netflix_titles.csv", stringsAsFactors = FALSE, na.strings = c("", "NA"))

conteudos_um_pais <- netflix[
  !is.na(netflix$country) &
    trimws(netflix$country) != "" &
    !grepl(",", netflix$country),
]

paises_contagem <- sort(table(trimws(conteudos_um_pais$country)), decreasing = TRUE)
top10_paises <- head(paises_contagem, 10)

top10_df <- data.frame(
  Pais = names(top10_paises),
  Total_de_conteudos = as.integer(top10_paises),
  row.names = NULL
)

plot_ly(
  type = "table",
  header = list(
    values = c("País", "Total de conteúdos"),
    align = "center",
    fill = list(color = "gray"),
    font = list(color = "white")
  ),
  cells = list(
    values = list(top10_df$Pais, top10_df$Total_de_conteudos),
    align = "center"
  )
)

Questão 9

library(plotly)

netflix <- read.csv("netflix_titles.csv", stringsAsFactors = FALSE, na.strings = c("", "NA"))
netflix$decada <- floor(netflix$release_year / 10) * 10

contagem_decada <- as.data.frame(table(netflix$decada, netflix$type), stringsAsFactors = FALSE)
names(contagem_decada) <- c("Decada", "Tipo", "Total")
contagem_decada$Decada <- as.numeric(as.character(contagem_decada$Decada))

dados_series <- contagem_decada[contagem_decada$Tipo == "TV Show", ]
dados_filmes <- contagem_decada[contagem_decada$Tipo == "Movie", ]

plot_ly() %>%
  add_lines(
    data = dados_series,
    x = ~Decada,
    y = ~Total,
    name = "TV Series",
    mode = "lines+markers",
    line = list(color = "blue"),
    marker = list(color = "blue")
  ) %>%
  add_lines(
    data = dados_filmes,
    x = ~Decada,
    y = ~Total,
    name = "Movies",
    mode = "lines+markers",
    line = list(color = "yellow"),
    marker = list(color = "yellow")
  ) %>%
  layout(
    title = "Quantidade de conteúdos da Netflix por década",
    xaxis = list(title = "Década"),
    yaxis = list(title = "Qtd. de Conteúdo")
  )

Questão 10

library(plotly)

netflix <- read.csv("netflix_titles.csv", stringsAsFactors = FALSE, na.strings = c("", "NA"))

generos <- c("Dramas", "Action & Adventure", "Comedies")
anos <- 2000:2010

filmes <- netflix[
  netflix$type == "Movie" &
    netflix$release_year %in% anos &
    !is.na(netflix$listed_in),
]

filmes$genero_principal <- trimws(sub(",.*", "", filmes$listed_in))
filmes <- filmes[filmes$genero_principal %in% generos, ]

tabela_generos <- as.data.frame(
  table(filmes$release_year, filmes$genero_principal),
  stringsAsFactors = FALSE
)
names(tabela_generos) <- c("Ano", "Genero", "Total")
tabela_generos$Ano <- as.integer(as.character(tabela_generos$Ano))

grade <- expand.grid(Ano = anos, Genero = generos, stringsAsFactors = FALSE)
dados_barras <- merge(grade, tabela_generos, by = c("Ano", "Genero"), all.x = TRUE)
dados_barras$Total[is.na(dados_barras$Total)] <- 0

cores_generos <- c(
  "Dramas" = "blue",
  "Action & Adventure" = "orange",
  "Comedies" = "green"
)

fig <- plot_ly()
for (genero in generos) {
  dados_genero <- dados_barras[dados_barras$Genero == genero, ]
  fig <- fig %>%
    add_bars(
      data = dados_genero,
      x = ~Ano,
      y = ~Total,
      name = genero,
      marker = list(color = cores_generos[genero])
    )
}

fig %>%
  layout(
    title = "Filmes por gênero principal entre 2000 e 2010",
    barmode = "group",
    xaxis = list(title = "Ano de Lançamento"),
    yaxis = list(title = "Qtd. de Lançamentos")
  )