Ejercicio 1. Franquicia de Stars Wars

Analizarás las cifras de taquilla de la franquicia de Star Wars. En el editor se definen tres vectores de las 3 primeras películas de Star Wars, las componentes indica el ingreso de las taquillas de EEUU y por fuera de EEUU.

new_hope <- c(460.998,314.4)
empire_strikes <- c(290.475,247.900)
return_jedi <- c(309.306,165.8)

1. Construye una matriz llamada star_wars_matrix de 2 × 3 que combine los 3 vectores.

star_wars_matrix<-matrix(data = c(new_hope,empire_strikes,return_jedi),nrow=2, ncol = 3, byrow = FALSE)
print(star_wars_matrix)
##         [,1]    [,2]    [,3]
## [1,] 460.998 290.475 309.306
## [2,] 314.400 247.900 165.800

2. Renombra las filas (“US”,“non-US”) y columnas (“A New Hope”, “The empire Strikes Back”,“Return of the Jedi”). Use rownames y colnames.

row.names(star_wars_matrix)<-c("US","non-US")
colnames(star_wars_matrix)<-c('new_hope','empire_strikes','return_jedi')
print(star_wars_matrix)
##        new_hope empire_strikes return_jedi
## US      460.998        290.475     309.306
## non-US  314.400        247.900     165.800

3. Calcule las cifras de la taquilla mundial de las tres películas y póngalas en el vector llamado worldwide_vector.

worldwide_vector<-colSums(star_wars_matrix)
print(worldwide_vector)
##       new_hope empire_strikes    return_jedi 
##        775.398        538.375        475.106

4. Añade worldwide_vector como una nueva fila a la matriz star_wars_matrix y al resultado le asignas el nombre all_wars_matrix.

all_wars_matrix<-rbind(star_wars_matrix, worldwide_vector)
print(all_wars_matrix)
##                  new_hope empire_strikes return_jedi
## US                460.998        290.475     309.306
## non-US            314.400        247.900     165.800
## worldwide_vector  775.398        538.375     475.106

5. Selecciona los ingresos no estadosunidenses de las películas y almacénalas como non_us_all. Además, calcule el promedio

non_us_all<-all_wars_matrix['non-US',]
print(non_us_all)
##       new_hope empire_strikes    return_jedi 
##          314.4          247.9          165.8

Promedio

mean_non_us_all<-mean(non_us_all)
print(mean_non_us_all)
## [1] 242.7

Ejercicio 2. El sistema solar

name <- c('Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune')
type <- c('Terrestrial planet', 'Terrestrial planet', 'Terrestrial planet', 'Terrestrial planet', 'Gas giant', 'Gas giant', 'Gas giant', 'Gas giant')
diameter <- c(0.382, 0.949, 1, 0.532, 11.209, 9.449, 4.007, 3.883)
rotation <- c(58.64, -243.02, 1, 1.03, 0.41, 0.43, -0.72, 0.67)
rings <- c(FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE)

Crea el marco de datos (data.frame), asignelo a planets_df y usa str() para ver la estructura.

planets_df<-data.frame(cbind(name,type,diameter,rotation,rings))
print(planets_df)
##      name               type diameter rotation rings
## 1 Mercury Terrestrial planet    0.382    58.64 FALSE
## 2   Venus Terrestrial planet    0.949  -243.02 FALSE
## 3   Earth Terrestrial planet        1        1 FALSE
## 4    Mars Terrestrial planet    0.532     1.03 FALSE
## 5 Jupiter          Gas giant   11.209     0.41  TRUE
## 6  Saturn          Gas giant    9.449     0.43  TRUE
## 7  Uranus          Gas giant    4.007    -0.72  TRUE
## 8 Neptune          Gas giant    3.883     0.67  TRUE

Estructura de los datos

str(planets_df)
## 'data.frame':    8 obs. of  5 variables:
##  $ name    : chr  "Mercury" "Venus" "Earth" "Mars" ...
##  $ type    : chr  "Terrestrial planet" "Terrestrial planet" "Terrestrial planet" "Terrestrial planet" ...
##  $ diameter: chr  "0.382" "0.949" "1" "0.532" ...
##  $ rotation: chr  "58.64" "-243.02" "1" "1.03" ...
##  $ rings   : chr  "FALSE" "FALSE" "FALSE" "FALSE" ...

1. Selecciona el diámetro del planeta Mercurio y todos los datos del planeta Marte.

Diametro de Mercurio

planets_df[1,3]
## [1] "0.382"

Datos del planeta Marte

planets_df[4,]

2. Seleccione e imprima los 5 primeros valores de la variable diameter de planets_df.

head(planets_df$diameter,5)
## [1] "0.382"  "0.949"  "1"      "0.532"  "11.209"

3. Escriba 3 formas de seleccionar la variable rings de planets_df y asígnelo a rings_vector

1° forma

planets_df$rings
## [1] "FALSE" "FALSE" "FALSE" "FALSE" "TRUE"  "TRUE"  "TRUE"  "TRUE"

2° forma

planets_df['rings']

3° forma

planets_df[, 5]
## [1] "FALSE" "FALSE" "FALSE" "FALSE" "TRUE"  "TRUE"  "TRUE"  "TRUE"

Ring vector

rings_vector<-planets_df[, 5]

4. Selecciona todos los planetas que tienen anillos. Use rings_vector.

planets_df[rings_vector == TRUE, ]

5. Utilice subset() en planets_df para seleccionar los planetas que tienen un diámetro menor que la Tierra. Como la variable diámetro es una medida relativa del diámetro del planeta con respecto al de la Tierra, su condición es diameter < 1.

subset(planets_df, diameter < 1)

6. Ordena de menor a mayor todos los planetas por diameter.

planets_df[order(diameter), ]

Ejercicio 3. Cine

Siendo un gran aficionado al cine, decides empezar a almacenar información sobre buenas películas, con la ayuda de listas.

Crea el código en el editor y asígnala a Batman_vs_ Superman_list; contiene tres elementos

Crea el codigo en el editor y asignala a sp man no way home list; contiene tres elementos.

*moviename: una cadena de caracteres con el tıtulo de la pelicula (almacenada en mov)

*actors: un vector con los nombres de los actores principales (almacenado en act). Solo 5 actores

*reviews: un marco de datos que contiene algunas crıticas (almacenado en rev). Solo 3 columnas (scores, sources, comments) y 3 filas.

mov <- "Batman Vs Superman"
act<-c('Ben Affleck','Henry Cavill','Gal Gadot','Jesse Eisenberg','Jeremy Irons')
score <- c(8, 9, 10)
source <- c('https://www.imdb.com/review/rw8007899/?ref_=tt_urv','https://www.imdb.com/review/rw8007526/?ref_=tt_urv','https://www.imdb.com/review/rw8007345/?ref_=tt_urv')
review <- c("If you've only given Batman v Superman, BvS, once, or havnt given it a shot due to divisive reviews give the directors a shot. This film fills in the holes and expands the story and characters enough that certain scenes mean alot more and certain views are more understandable. Its not crazy different from the theatrical version, but enough warrant a better score and ultimately make BvS a better film. Man of Steel, BvS Directors cut and Zack Snyders Justice League, when viewed in the order are a decent trilogy in their own right and enjoyable for the fans of DC comics...","This isn't just a movie it's much more than that. Connecting the CB characters with the real world and the way Zack executed it was par excellence. It's an underappreciated movie which will be talked eventually too.","This is much better then the one that was released in the cinema do not understand while they cut it down to being with. The story made so much more since with everything in you understood while Bruce Wayne actor the way he did because of what lex Luther was do behind the scene.")

Marco de Datos de Criticas

rev <- data.frame(cbind(score, source, review))
rev

Lista de informacion de la pelicula

Batman_vs_Superman_list<- list(moviename = mov, actors = act, reviews = rev)
Batman_vs_Superman_list
## $moviename
## [1] "Batman Vs Superman"
## 
## $actors
## [1] "Ben Affleck"     "Henry Cavill"    "Gal Gadot"       "Jesse Eisenberg"
## [5] "Jeremy Irons"   
## 
## $reviews
##   score                                             source
## 1     8 https://www.imdb.com/review/rw8007899/?ref_=tt_urv
## 2     9 https://www.imdb.com/review/rw8007526/?ref_=tt_urv
## 3    10 https://www.imdb.com/review/rw8007345/?ref_=tt_urv
##                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             review
## 1 If you've only given Batman v Superman, BvS, once, or havnt given it a shot due to divisive reviews give the directors a shot. This film fills in the holes and expands the story and characters enough that certain scenes mean alot more and certain views are more understandable. Its not crazy different from the theatrical version, but enough warrant a better score and ultimately make BvS a better film. Man of Steel, BvS Directors cut and Zack Snyders Justice League, when viewed in the order are a decent trilogy in their own right and enjoyable for the fans of DC comics...
## 2                                                                                                                                                                                                                                                                                                                                                                          This isn't just a movie it's much more than that. Connecting the CB characters with the real world and the way Zack executed it was par excellence. It's an underappreciated movie which will be talked eventually too.
## 3                                                                                                                                                                                                                                                                                                          This is much better then the one that was released in the cinema do not understand while they cut it down to being with. The story made so much more since with everything in you understood while Bruce Wayne actor the way he did because of what lex Luther was do behind the scene.

Vector de actores

Selecciona de Batman_vs_Superman_list el vector que representa a los actores. Simplemente imprime este vector.

Batman_vs_Superman_list["actors"]
## $actors
## [1] "Ben Affleck"     "Henry Cavill"    "Gal Gadot"       "Jesse Eisenberg"
## [5] "Jeremy Irons"

Seleccion del segundo actor

Selecciona de Batman_vs_Superman_list el segundo elemento del vector que representa a los actores. Haz una impresión como la anterior.

Batman_vs_Superman_list$actors[2]
## [1] "Henry Cavill"

Ejercicio 4. Lanzamiento de una moneda

Realice 1000 simulaciones del lanzamiento de una moneda equilibrada y compruebe experimentalmente que el número de veces que aparece una cara entre el total de lanzamientos se aproxima a 1/2 conforme el número de lanzamientos crece.

Simulación

caras_moneda <-c('cara','sello')
intento<-1000
simulacion_mon <- data.frame(num_lanza = 0,
                         resul_sim=0,
                         num_cara=0,
                         prob_acum=0)
sum_cara=0
for(i in 1:intento) {
  simulacion_mon[i,'resul_sim']<-sample(caras_moneda,size=1)
  simulacion_mon[i,"num_lanza"]<-i
  if(simulacion_mon[i,'resul_sim']=='cara'){
    sum_cara<-sum_cara+1
  }
  simulacion_mon[i,"num_cara"]<-sum_cara
  simulacion_mon[i,"prob_acum"]<-simulacion_mon[i,"num_cara"]/simulacion_mon[i,"num_lanza"]
}   

simulacion_mon

Representacion Gráfica

graph_plot <- simulacion_mon %>% ggplot(aes(y =prob_acum, x = num_lanza)) + ggtitle("Probabilidad de obtener cara al lanzar una moneda") + geom_point(color = "#EE3B3B")+ ylim(0,1)+ labs(x='Numero de intentos', y='Probabilidad Acumulada')
graph_plot

Se evidencia a trave´s de la grafica que al simular 1000 veces el lanzamientode una moneda la probabilidad de que salga cara tiende al 50%

Ejercicio 5. Lanzamiento de un dado

Realice 1000 simulaciones del lanzamiento de un dado equilibrado y compruebe experimentalmente que el número de veces que aparece una de las caras entre el total de lanzamientos se aproxima a 1/6 conforme el número de lanzamientos crece.

para realizar la simulacion, Tomaremos como nuestro evento favorable el evento donde se obtenga un seis como resultado

caras_dado <- c(1:6)
intento<-1000
simulacion_dado <- data.frame(num_lanza = 0,
                         resul_sim=0,
                         num_seis = 0,
                         prob_acum= 0)
sum_seis=0
for(i in 1:intento) {
  simulacion_dado[i,'resul_sim']<-sample(caras_dado,size=1)
  simulacion_dado[i,"num_lanza"]<-i
  if(simulacion_dado[i,'resul_sim']==6){
    sum_seis<-sum_seis+1
  }
  simulacion_dado[i,"num_seis"]<-sum_seis
  simulacion_dado[i,"prob_acum"]<-simulacion_dado[i,"num_seis"]/simulacion_dado[i,"num_lanza"]
}   

simulacion_dado   

Representacion Gráfica

lanz<-c(1:1000)
graph_2 <- simulacion_dado %>% ggplot(aes(y = prob_acum, x = lanz)) + ggtitle("Simulacion de la Probabilidad de obtener el numero seis al lanzar un Dado") + geom_point(color = "#EE3B3B")+ ylim(0,1)+ labs(x='Numero de intentos', y='Probabilidad Acumulada')
graph_2

Se evidencia a trave´s de la grafica que al simular 1000 veces el lanzamientode un dado la probabilidad de que salga cara tiende al 16,66%