Relatório ficha 12

options(repos = list(CRAN="http://cran.rstudio.com/"))

Quest 1

xlim <- c(0, 3)
ylim <- c(0, 518)

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

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

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)

plot(clock ,MRT_1F, type="o", pch=0, xlim=c(0, 3), ylim=c(0, 518), xlab="Time Response (sec.)", ylab="Time between Things requests (seconds)")

lines(clock, MRT_3F, type="o", col="yellow", pch=1)

lines(clock, MRT_5F, type="o", col="red", pch=2)

lines(clock, MRT_10F, type="o", col="blue", pch=3)

lines(clock, MRT_15F, type="o", col="purple", pch=4)

lines(clock, MRT_sem_F, type="o", col="green", pch=5)

layout(matrix(c(1, 2,
               1, 2,
               3, 4,
               3, 4,
               5, 6,
               5, 6
               ), nrow=3, ncol=2, byrow=TRUE))

colors <- c("#E6E6E6", "#666666")
log_MRT_1F <- log(MRT_1F)
bind_MRT_1F <- cbind(MRT_1F, log_MRT_1F)
val_MRT_1F <- matrix(bind_MRT_1F, nrow = 2, ncol = 7, byrow = TRUE)
barplot(val_MRT_1F, names.arg = clock, col = colors, beside=T, xlab="Time between Thngs requests", ylab="Response time (s)")
legend("topright", legend = c("w/aFog", "1 Fog"), col = colors, pch = c(15, 15))

log_MRT_3F <- log(MRT_3F)
bind_MRT_3F <- cbind(MRT_3F, log_MRT_3F)
val_MRT_3F <- matrix(bind_MRT_3F, nrow = 2, ncol = 7, byrow = TRUE)
barplot(val_MRT_1F, names.arg = clock, col = colors, beside=T, xlab="Time between Things requests", ylab="Response time (s)")
legend("topright", legend = c("w/aFog", "3 Fog"), col = colors, pch = c(15, 15))

log_MRT_5F <- log(MRT_5F)
bind_MRT_5F <- cbind(MRT_5F, log_MRT_5F)
val_MRT_5F <- matrix(bind_MRT_1F, nrow = 2, ncol = 7, byrow = TRUE)
barplot(val_MRT_5F, names.arg = clock, col = colors, beside=T, xlab="Time between Things requests", ylab="Response time (s)")
legend("topright", legend = c("w/aFog", "5 Fog"), col = colors, pch = c(15, 15))

log_MRT_10F <- log(MRT_10F)
bind_MRT_10F <- cbind(MRT_10F, log_MRT_10F)
val_MRT_10F <- matrix(bind_MRT_10F, nrow = 2, ncol = 7, byrow = TRUE)
barplot(val_MRT_10F, names.arg = clock, col = colors, beside=T, xlab="Time between Things requests", ylab="Response time (s)")
legend("topright", legend = c("w/aFog", "10 Fog"), col = colors, pch = c(15, 15))

log_MRT_15F <- log(MRT_15F)
bind_MRT_15F <- cbind(MRT_15F, log_MRT_15F)
val_MRT_15F <- matrix(bind_MRT_15F, nrow = 2, ncol = 7, byrow = TRUE)
barplot(val_MRT_1F, main="Grafico name", names.arg = clock, col = colors, beside=T, xlab="Time between Thngs requests", ylab="Response time (s)")
legend("topright", legend = c("w/aFog", "15 Fog"), col = colors, pch = c(15, 15))

Questão 2

# Instalar e carregar os pacotes necessários

if (!requireNamespace("tidyverse", quietly = TRUE)) {
install.packages("tidyverse")
}

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.0
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
# Criar as categorias e os valores
quality_ratings <- c("Good", "Very Good", "Excellent")
metal_prices <- c("$10-19", "$20-29", "$30-39", "$40-49")

# Criar a matriz
matriz <- matrix(c(
  "Good", 53.8, 33.9, 2.6, 0.0,
  "Very Good", 43.6, 54.2, 60.5, 21.4,
  "Excellent", 2.6, 11.9, 36.8, 78.6
), nrow = length(quality_ratings), byrow = TRUE)

# Converter a matriz em um data frame
df <- as.data.frame(matriz)

# Ajustar os nomes das colunas
colnames(df) <- c("Quality_Rating", metal_prices)

# Converter os valores para numéricos
df[, -1] <- sapply(df[, -1], as.numeric)

# Criar o gráfico de barras empilhadas usando barplot()
barplot(
  t(as.matrix(df[, -1])),  # Transpor os dados
  beside = TRUE,  # Barras empilhadas lado a lado
  col = c("plum4", "orchid", "purple", "purple4"), # Cores para as barras
  legend.text = FALSE,  # Adicionar legenda
  args.legend = list(x = "topright"),  # Posição da legenda
  main = "Qualidade de refeição",  # Título principal
  xlab = "Quality Rating",  # Rótulo do eixo x
  ylab = "Porcentagem (%)",  # Rótulo do eixo y
  names.arg = df$Quality_Rating,  # Nomes no eixo x
  ylim = c(0, 100)  # Limite do eixo y
)

# Adicionar legenda com Titulo, posição e cores certas
legend("topleft", title = " Metal Prices ", legend = metal_prices, fill = c("plum4", "orchid", "purple", "purple4"))

Questao 3

# Questão 3
# Carregue o conjunto de dados airquality
data(airquality)

# Converta as temperaturas para graus Celsius
airquality$Temp_Celsius <- (airquality$Temp - 32) / 1.8

# Crie o histograma com a função hist()
hist_plot <- hist(airquality$Temp_Celsius, breaks = 20, col = "lightblue", main = "Histograma das Temperaturas em Graus Celsius (Maio)", xlab = "Temperatura (°C)", ylab = "Frequência", probability = TRUE)

# Adicione a curva de densidade
lines(density(airquality$Temp_Celsius), col = "blue", lwd = 2)

# Adicione a legenda
legend("topright", legend = c("Densidade"), col = c("blue"), lwd = 2)

Questao 4

# Questão 4
# Instalar e carregar o pacote necessários

if (!requireNamespace("dplyr", quietly = TRUE)) {
install.packages("dplyr")
}
library(dplyr)

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

# Calcular a porcentagem total de vendas por país
sales_percent <- sales %>%
  mutate(Percentage = (sales$SALES / sum(sales$SALES)) * 100)

# Criar o gráfico de pizza
pie(sales_percent$Percentage, labels = paste(sales_percent$COUNTRY, "\n", round(sales_percent$Percentage, 1), "%"), col = rainbow(length(sales_percent$COUNTRY)))

# Adicionar título ao gráfico
title("Porcentagem Total de Vendas por País")

# Adicionar legenda
legend("topright", legend = sales_percent$COUNTRY, fill = rainbow(length(sales_percent$COUNTRY)), title = "País")

Questao 5

# Questão 5
# Carregar o conjunto de dados InsectSprays
data(InsectSprays)

# Criar um boxplot sem outliers
boxplot(count ~ spray, data = InsectSprays, col = "yellow", outline = FALSE,
        main = "Boxplot de Contagens de Insetos por Tipo de Inseticida",
        xlab = "Tipo de Inseticida", ylab = "Contagem de Insetos")

Questão 6

if (!requireNamespace("dplyr", quietly = TRUE)) {
  install.packages("dplyr")
}

if (!requireNamespace("lubridate", quietly = TRUE)) {
  install.packages("lubridate")
}

library(dplyr)
library(lubridate)

data_0.1 <- read_csv("monitoringCloudData_0.1.csv", show_col_types = FALSE)
data_0.5 <- read_csv("monitoringCloudData_0.5.csv", show_col_types = FALSE)
data_1 <- read_csv("monitoringCloudData_1.csv", show_col_types = FALSE)
data_NONE <- read_csv("monitoringCloudData_NONE.csv", show_col_types = FALSE)

# Ajuste da coluna 'currentTime'
adjust_time <- function(data) {
  data <- data %>%
    mutate(currentTime = ymd_hms(currentTime)) %>%
    mutate(time_diff = difftime(currentTime, min(currentTime), units = "hours"))
  
  return(data)
}

data_0.1 <- adjust_time(data_0.1)
data_0.5 <- adjust_time(data_0.5)
data_1 <- adjust_time(data_1)
data_NONE <- adjust_time(data_NONE)

# Ajuste da coluna 'usedMemory'
adjust_memory <- function(data) {
  data <- data %>%
    mutate(usedMemory_MB = case_when(
      str_detect(usedMemory, "TB") ~ parse_number(usedMemory) * 1000000,
      str_detect(usedMemory, "GB") ~ parse_number(usedMemory) * 1024,
      str_detect(usedMemory, "MB") ~ parse_number(usedMemory),
      TRUE ~ as.numeric(usedMemory)
    ))
  
  return(data)
}

data_0.1 <- adjust_memory(data_0.1)
data_0.5 <- adjust_memory(data_0.5)
data_1 <- adjust_memory(data_1)
data_NONE <- adjust_memory(data_NONE)


# Organizando os gráficos com layout
layout(matrix(c(1, 2,
                3, 4)
              , nrow = 2, byrow = TRUE))

# Gráfico NONE
plot_NONE <- ggplot(data_NONE, aes(x = time_diff, y = usedMemory_MB)) +
  geom_line() +
  labs(title = "monitoringCloudData_NONE", x = "Time (hours)", y = "Used Memory (MB)")
print(plot_NONE)
## Don't know how to automatically pick scale for object of type <difftime>.
## Defaulting to continuous.

# Gráfico 0.1
plot_0.1 <- ggplot(data_0.1, aes(x = time_diff, y = usedMemory_MB)) +
  geom_line() +
  labs(title = "monitoringCloudData_0.1", x = "Time (hours)", y = "Used Memory (MB)")
print(plot_0.1)
## Don't know how to automatically pick scale for object of type <difftime>.
## Defaulting to continuous.

# Gráfico 0.5
plot_0.5 <- ggplot(data_0.5, aes(x = time_diff, y = usedMemory_MB)) +
  geom_line() +
  labs(title = "monitoringCloudData_0.5", x = "Time (hours)", y = "Used Memory (MB)")
print(plot_0.5)
## Don't know how to automatically pick scale for object of type <difftime>.
## Defaulting to continuous.

# Gráfico 1
plot_1 <- ggplot(data_1, aes(x = time_diff, y = usedMemory_MB)) +
  geom_line() +
  labs(title = "monitoringCloudData_1", x = "Time (hours)", y = "Used Memory (MB)")
print(plot_1)
## Don't know how to automatically pick scale for object of type <difftime>.
## Defaulting to continuous.

Questao 7

if (!requireNamespace("dplyr", quietly = TRUE)) {
  install.packages("dplyr")
}

if (!requireNamespace("plotly", quietly = TRUE)) {
  install.packages("plotly")
}

library(dplyr)
library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
netflix_titles <- read.csv(file = "netflix_titles.csv",
                            header = TRUE,
                            strip.white = TRUE,
                            na.strings = "")
netflix_titles <- netflix_titles %>%
  filter(!is.na(country) & country != "" & !grepl(",", country)) %>%
  filter(!is.na(country) & country != "" & !grepl(",", country))
top_countries <- netflix_titles %>%
  group_by(country) %>%
  summarise(count = n()) %>%
  arrange(desc(count)) %>%
  head(10)
plot_ly(labels = top_countries$country, values = top_countries$count, type = "pie",
        textinfo = "label+percent", insidetextfont = list(color = "#FFFFFF"),
        hoverinfo = "label+percent", hole = 0.6) %>%
  layout(title = "Top 10 Países com Mais Conteúdo na Netflix",
         xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
         yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
         width = 900,  
         height = 800)  

Questão 8

if (!requireNamespace("dplyr", quietly = TRUE)) {
  install.packages("dplyr")
}

if (!requireNamespace("plotly", quietly = TRUE)) {
  install.packages("plotly")
}

library(dplyr)
library(plotly)
top_countries <- netflix_titles %>%
  group_by(country) %>%
  summarise(count = n()) %>%
  arrange(desc(count)) %>%
  head(10)

table <- plot_ly(
  type = "table",
  header = list(values = c("País", "Total de Conteúdos"),
                fill = list(color = "#a9a9a9"),
                align = c("center"),
                font = list(color = "white", size = 15)),
  cells = list(values = list(top_countries$country, top_countries$count),
               align = c("center"),
               font = list(color = c("black", "black"), size = 12))
)

table

Questão 9

if (!requireNamespace("dplyr", quietly = TRUE)) {
  install.packages("dplyr")
}

if (!requireNamespace("plotly", quietly = TRUE)) {
  install.packages("plotly")
}
library(dplyr)
library(plotly)

netflix <- read.csv("netflix_titles.csv")

#cria e adiciona uma coluna no dataframe em que cada linha é a década correspondente
#ao release_year
netflix <- netflix %>%
  mutate(decade = 10 * (release_year %/% 10))

#cria um dataframe com os filmes lançados por década
filmesPorDecada <- netflix %>%
  filter(type == "Movie") %>%
  group_by(decade) %>%
  summarise(qtd_conteúdo = n())

#cria um dataframe com as séries lançadas por década
seriesPorDecada <- netflix %>%
  filter(type == "TV Show") %>%
  group_by(decade) %>%
  summarise(num_series = n())

#junta os dois dataframes
seriesFilmes <- left_join(filmesPorDecada, seriesPorDecada, by = "decade")
#atribui valor perdido (1) na segunda linha de num_series na junção dos dataframes
seriesFilmes$num_series[2] <- 1

#qtd_conteúdo: num_filmes, mas tive que renomear pra aparecer certinho no gráfico

fig <- plot_ly(
    seriesFilmes, 
    x = ~decade
) %>%
  add_trace(
    y = ~qtd_conteúdo,
    name = 'Filmes',
    mode = 'lines+markers'
  ) %>%
  add_trace(
    y = ~num_series,
    name = 'Séries',
    mode = 'lines+markers'
  )
fig
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plotly.com/r/reference/#scatter
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plotly.com/r/reference/#scatter

Questão 10

if (!requireNamespace("dplyr", quietly = TRUE)) {
  install.packages("dplyr")
}

if (!requireNamespace("plotly", quietly = TRUE)) {
  install.packages("plotly")
}

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

netflix <- read.csv("netflix_titles.csv")


#cria um dataframe apenas com filmes lançados entre 2000 e 2010
df_filtrado <- netflix %>%
  filter(between(release_year, 2000, 2010) & type == "Movie") %>%
  select(release_year, listed_in)

#para contar a quantidade de filmes de cada categoria lançados em cada ano 2000~2010
contagem_categorias_por_ano <- df_filtrado %>%
  mutate(primeira_categoria = ifelse(str_detect(listed_in, ","), word(listed_in, 1, sep = ", "), listed_in)) %>%
  group_by(release_year, primeira_categoria) %>%
  summarise(num_filmes = n())
## `summarise()` has grouped output by 'release_year'. You can override using the
## `.groups` argument.
#para considerar apenas as linhas com as categorias desejadas
categorias <- c("Action & Adventure", "Comedies", "Dramas")
df_final <- contagem_categorias_por_ano %>%
  filter(primeira_categoria %in% categorias)

#criar df com os anos
df_grafico <- data.frame(release_year = 2000:2010)

#juntar tudo em um dataframe
df_grafico <- df_grafico %>%
  left_join(
    df_final %>%
      filter(str_detect(primeira_categoria, "Comedies")) %>%
      select(release_year, num_filmes) %>%
      rename(Comedies = num_filmes),
    by = "release_year"
  ) %>%
  left_join(
    df_final %>%
      filter(str_detect(primeira_categoria, "Dramas")) %>%
      select(release_year, num_filmes) %>%
      rename(Dramas = num_filmes),
    by = "release_year"
  ) %>%
  left_join(
    df_final %>%
      filter(str_detect(primeira_categoria, "Action & Adventure")) %>%
      select(release_year, num_filmes) %>%
      rename(`ActionAdventure` = num_filmes),
    by = "release_year"
  )

#gera o gráfico
fig <- plot_ly(
  df_grafico,
  x = ~release_year,
  y = ~Comedies,
  type = 'bar',
  name = 'Comédia'
) %>%
  add_trace(
    y = ~Dramas,
    name = 'Drama'
  ) %>%
  add_trace(
    y = ~ActionAdventure,
    name = 'Ação e Aventura'
  ) %>%
  layout(
    yaxis = list(title = 'Qnt. de Lançamentos'),
    xaxis = list(title = 'Ano de Lançamento')
)

#exibir gráfico
fig