library(tidyverse)
## Warning: package 'tidyverse' was built under R version 4.3.2
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.3     ✔ 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

Q1. (a)

 # Assuming starwars is your dataset
average_mass_by_gender <- starwars %>%
  group_by(gender) %>%
  summarise(
    average_mass = mean(mass, na.rm = TRUE)
  ) %>%
  arrange(average_mass)

print(average_mass_by_gender)
## # A tibble: 3 × 2
##   gender    average_mass
##   <chr>            <dbl>
## 1 <NA>              48  
## 2 feminine          54.7
## 3 masculine        106.
starwars_data <- dplyr::starwars

# Convert height from cm to meters
starwars_data <- starwars_data %>%
  mutate(height_meters = height / 100)

# Add a new variable for BMI
starwars_data <- starwars_data %>%
  mutate(bmi = mass / height_meters^2)

# Print the updated dataset with BMI
print(starwars_data)
## # A tibble: 87 × 16
##    name     height  mass hair_color skin_color eye_color birth_year sex   gender
##    <chr>     <int> <dbl> <chr>      <chr>      <chr>          <dbl> <chr> <chr> 
##  1 Luke Sk…    172    77 blond      fair       blue            19   male  mascu…
##  2 C-3PO       167    75 <NA>       gold       yellow         112   none  mascu…
##  3 R2-D2        96    32 <NA>       white, bl… red             33   none  mascu…
##  4 Darth V…    202   136 none       white      yellow          41.9 male  mascu…
##  5 Leia Or…    150    49 brown      light      brown           19   fema… femin…
##  6 Owen La…    178   120 brown, gr… light      blue            52   male  mascu…
##  7 Beru Wh…    165    75 brown      light      blue            47   fema… femin…
##  8 R5-D4        97    32 <NA>       white, red red             NA   none  mascu…
##  9 Biggs D…    183    84 black      light      brown           24   male  mascu…
## 10 Obi-Wan…    182    77 auburn, w… fair       blue-gray       57   male  mascu…
## # ℹ 77 more rows
## # ℹ 7 more variables: homeworld <chr>, species <chr>, films <list>,
## #   vehicles <list>, starships <list>, height_meters <dbl>, bmi <dbl>
     # Assuming starwars is your dataset
starwars_with_bmi <- starwars %>%
  mutate(bmi = mass / ((height / 100)^2))  # Assuming height is in centimeters

average_bmi_by_species <- starwars_with_bmi %>%
  group_by(species) %>%
  summarise(
    average_bmi = mean(bmi, na.rm = TRUE)
  ) %>%
  arrange(average_bmi)

# Find species with the lowest average BMI
lowest_bmi_species <- average_bmi_by_species %>%
  filter(average_bmi == min(average_bmi, na.rm = TRUE)) %>%
  pull(species)

# Find species with the highest average BMI
highest_bmi_species <- average_bmi_by_species %>%
  filter(average_bmi == max(average_bmi, na.rm = TRUE)) %>%
  pull(species)

# Display the species with the lowest and highest average BMI
cat("Species with the lowest average BMI:", lowest_bmi_species, "\n")
## Species with the lowest average BMI: Skakoan
cat("Species with the highest average BMI:", highest_bmi_species, "\n")
## Species with the highest average BMI: Hutt
  # Assuming your dataset is named "starwars"
starwars_with_nfilms <- starwars %>%
  mutate(nfilms = lengths(films))

# Display the updated dataset with the new variable
print(starwars_with_nfilms)
## # A tibble: 87 × 15
##    name     height  mass hair_color skin_color eye_color birth_year sex   gender
##    <chr>     <int> <dbl> <chr>      <chr>      <chr>          <dbl> <chr> <chr> 
##  1 Luke Sk…    172    77 blond      fair       blue            19   male  mascu…
##  2 C-3PO       167    75 <NA>       gold       yellow         112   none  mascu…
##  3 R2-D2        96    32 <NA>       white, bl… red             33   none  mascu…
##  4 Darth V…    202   136 none       white      yellow          41.9 male  mascu…
##  5 Leia Or…    150    49 brown      light      brown           19   fema… femin…
##  6 Owen La…    178   120 brown, gr… light      blue            52   male  mascu…
##  7 Beru Wh…    165    75 brown      light      blue            47   fema… femin…
##  8 R5-D4        97    32 <NA>       white, red red             NA   none  mascu…
##  9 Biggs D…    183    84 black      light      brown           24   male  mascu…
## 10 Obi-Wan…    182    77 auburn, w… fair       blue-gray       57   male  mascu…
## # ℹ 77 more rows
## # ℹ 6 more variables: homeworld <chr>, species <chr>, films <list>,
## #   vehicles <list>, starships <list>, nfilms <int>
 # Assuming your dataset is named "starwars_with_nfilms"
character_max_films <- starwars_with_nfilms %>%
  filter(nfilms == max(nfilms)) %>%
  pull(name)

# Display the names of characters with the maximum number of films
print(character_max_films)
## [1] "R2-D2"

Q2Question.

# Assuming d is your dataset
d <- read_csv("C:\\Users\\MD IMRAN\\AppData\\Local\\RStudio\\top40Univ.csv")
## Rows: 40 Columns: 10
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (2): Institution, Location
## dbl (8): World Rank, National Rank, Quality of Education, Publications, Infl...
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# Load necessary libraries
library(dplyr)

# Use mutate to make Quality of Education numeric
d <- d %>%
  mutate(`Quality of Education` = as.numeric(`Quality of Education`))
# Summarize the location with counts
location_counts <- d %>%
  group_by(Location) %>%
  summarise(University_Count = n())

# Find the location with the highest number of top 40 universities
max_location <- location_counts %>%
  filter(University_Count == max(University_Count)) %>%
  select(Location, University_Count)

# Print the summarized location counts
print(location_counts)
## # A tibble: 8 × 2
##   Location       University_Count
##   <chr>                     <int>
## 1 Canada                        1
## 2 France                        2
## 3 Israel                        2
## 4 Japan                         4
## 5 South Korea                   1
## 6 Switzerland                   1
## 7 USA                          25
## 8 United Kingdom                4
# Print the location with the highest number of top 40 universities
print(max_location)
## # A tibble: 1 × 2
##   Location University_Count
##   <chr>               <int>
## 1 USA                    25
# Summarize the location with counts
location_counts <- d %>%
  group_by(Location) %>%
  summarise(University_Count = n())

# Create a barplot using ggplot2
ggplot(location_counts, aes(x = Location, y = University_Count)) +
  geom_bar(stat = "identity", fill = "skyblue") +
  labs(title = "Top 40 Universities by Location",
       x = "Location",
       y = "Number of Universities") +
  theme_minimal()

(d)

# Reorder the Location factor in decreasing order of counts
location_counts <- location_counts %>%
  mutate(Location = fct_reorder(Location, University_Count, .desc = TRUE))

# Create a barplot using ggplot2 with bars in decreasing order
ggplot(location_counts, aes(x = Location, y = University_Count)) +
  geom_bar(stat = "identity", fill = "skyblue") +
  labs(title = "Top 40 Universities by Location",
       x = "Location",
       y = "Number of Universities") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))  # Rotate x-axis labels for better readability

(e)

top5 <- function(x) {
  sum(x %in% 1:5, na.rm = TRUE)
}

# Test the function with given vectors
x1 <- c(NA, 10:1)
x2 <- c(6, 2, 8, 9, -1, 0, 4)

result_x1 <- top5(x1)
result_x2 <- top5(x2)

print(result_x1)  
## [1] 5
print(result_x2)  
## [1] 2
# Define the top5 function
top5 <- function(x) {
  sum(x %in% 1:5, na.rm = TRUE)
}

# Use rowwise and mutate to calculate top5 for each university
d <- d %>%
  rowwise() %>%
  mutate(
    Top5_Count = top5(c(`Quality of Education`, Publications, Influence, Citations, `Broad Impact`))
  )

# Print the updated dataset
print(d)
## # A tibble: 40 × 11
## # Rowwise: 
##    `World Rank` Institution      Location `National Rank` `Quality of Education`
##           <dbl> <chr>            <chr>              <dbl>                  <dbl>
##  1            1 Harvard Univers… USA                    1                      1
##  2            2 Stanford Univer… USA                    2                      9
##  3            3 Massachusetts I… USA                    3                      3
##  4            4 University of C… United …               1                      2
##  5            5 University of O… United …               2                      7
##  6            6 Columbia Univer… USA                    4                     13
##  7            7 University of C… USA                    5                      5
##  8            8 University of C… USA                    6                     11
##  9            9 Princeton Unive… USA                    7                      4
## 10           10 Cornell Univers… USA                    8                     12
## # ℹ 30 more rows
## # ℹ 6 more variables: Publications <dbl>, Influence <dbl>, Citations <dbl>,
## #   `Broad Impact` <dbl>, Score <dbl>, Top5_Count <int>
# Load necessary libraries
library(dplyr)

# Define the top5 function
top5 <- function(x) {
  sum(x %in% 1:5, na.rm = TRUE)
}

# Use filter to get universities with at least one top 5 ranking
universities_with_top5 <- d %>%
  filter(
    top5(c(`Quality of Education`, Publications, Influence, Citations, `Broad Impact`)) > 0
  ) %>%
  select(Institution)

# Print the dataset containing names of universities with at least one top 5 ranking
print(universities_with_top5)
## # A tibble: 11 × 1
## # Rowwise: 
##    Institution                          
##    <chr>                                
##  1 Harvard University                   
##  2 Stanford University                  
##  3 Massachusetts Institute of Technology
##  4 University of Cambridge              
##  5 University of California, Berkeley   
##  6 Princeton University                 
##  7 Johns Hopkins University             
##  8 University of Michigan, Ann Arbor    
##  9 University of California, San Diego  
## 10 University of Washington - Seattle   
## 11 University of Toronto
# Add a new variable "Continent" using case_when
d <- d %>%
  mutate(
    Continent = case_when(
      Location %in% c("United States of America", "Canada") ~ "NorthAmerica",
      Location %in% c("Japan", "South Korea") ~ "Asia",
      TRUE ~ "Europe"
    )
  )

# Print the updated dataset with the new variable
print(d)
## # A tibble: 40 × 12
## # Rowwise: 
##    `World Rank` Institution      Location `National Rank` `Quality of Education`
##           <dbl> <chr>            <chr>              <dbl>                  <dbl>
##  1            1 Harvard Univers… USA                    1                      1
##  2            2 Stanford Univer… USA                    2                      9
##  3            3 Massachusetts I… USA                    3                      3
##  4            4 University of C… United …               1                      2
##  5            5 University of O… United …               2                      7
##  6            6 Columbia Univer… USA                    4                     13
##  7            7 University of C… USA                    5                      5
##  8            8 University of C… USA                    6                     11
##  9            9 Princeton Unive… USA                    7                      4
## 10           10 Cornell Univers… USA                    8                     12
## # ℹ 30 more rows
## # ℹ 7 more variables: Publications <dbl>, Influence <dbl>, Citations <dbl>,
## #   `Broad Impact` <dbl>, Score <dbl>, Top5_Count <int>, Continent <chr>
library(ggplot2)

# Plot Citations versus Broad Impact with different colors for continents
ggplot(d, aes(x = Citations, y = `Broad Impact`, color = Continent)) +
  geom_point() +
  labs(title = "Citations vs Broad Impact by Continent",
       x = "Citations",
       y = "Broad Impact") +
  theme_minimal()

Q3.a

 # Assuming you have loaded the tidyverse package
library(tidyverse)

# Load the dataset
a <- read_csv("C:\\Users\\MD IMRAN\\AppData\\Local\\RStudio\\academy_awards.csv")
## New names:
## Rows: 10137 Columns: 11
## ── Column specification
## ──────────────────────────────────────────────────────── Delimiter: "," chr
## (11): Year, Category, Nominee, Additional Info, Won?, ...6, ...7, ...8, ...
## ℹ Use `spec()` to retrieve the full column specification for this data. ℹ
## Specify the column types or set `show_col_types = FALSE` to quiet this message.
## • `` -> `...6`
## • `` -> `...7`
## • `` -> `...8`
## • `` -> `...9`
## • `` -> `...10`
## • `` -> `...11`
# Use select to pick the first 5 variables
a_selected <- a %>%
  select(1:5)

# Use separate with sep=4 to split the Year variable
a_selected <- a_selected %>%
  separate(Year, into = c("Actual_Year", "Instance"), sep = 4)

# Make the Actual_Year variable numeric
a_selected <- a_selected %>%
  mutate(Actual_Year = as.numeric(Actual_Year))

# Display the modified dataset
print(a_selected)
## # A tibble: 10,137 × 6
##    Actual_Year Instance  Category               Nominee `Additional Info` `Won?`
##          <dbl> <chr>     <chr>                  <chr>   <chr>             <chr> 
##  1        2010 " (83rd)" Actor -- Leading Role  Javier… Biutiful {'Uxbal… NO    
##  2        2010 " (83rd)" Actor -- Leading Role  Jeff B… True Grit {'Roos… NO    
##  3        2010 " (83rd)" Actor -- Leading Role  Jesse … The Social Netwo… NO    
##  4        2010 " (83rd)" Actor -- Leading Role  Colin … The King's Speec… YES   
##  5        2010 " (83rd)" Actor -- Leading Role  James … 127 Hours {'Aron… NO    
##  6        2010 " (83rd)" Actor -- Supporting R… Christ… The Fighter {'Di… YES   
##  7        2010 " (83rd)" Actor -- Supporting R… John H… Winter's Bone {'… NO    
##  8        2010 " (83rd)" Actor -- Supporting R… Jeremy… The Town {'James… NO    
##  9        2010 " (83rd)" Actor -- Supporting R… Mark R… The Kids Are All… NO    
## 10        2010 " (83rd)" Actor -- Supporting R… Geoffr… The King's Speec… NO    
## # ℹ 10,127 more rows
actress <- a |>
  filter(Category %in% c("Actress -- Leading Role", "Actress -- Supporting Role")) |>
  group_by(Nominee) |>
  summarise(
    Nominations = n(),
    Wins = sum(`Won?` == "YES"),
    First_Year = min(Year),
    Last_Year = max(Year)
  )

actress
## # A tibble: 429 × 5
##    Nominee         Nominations  Wins First_Year  Last_Year  
##    <chr>                 <int> <int> <chr>       <chr>      
##  1 Abigail Breslin           1     0 2006 (79th) 2006 (79th)
##  2 Adriana Barraza           1     0 2006 (79th) 2006 (79th)
##  3 Agnes Moorehead           4     0 1942 (15th) 1964 (37th)
##  4 Alfre Woodard             1     0 1983 (56th) 1983 (56th)
##  5 Ali MacGraw               1     0 1970 (43rd) 1970 (43rd)
##  6 Alice Brady               2     1 1936 (9th)  1937 (10th)
##  7 Aline MacMahon            1     0 1944 (17th) 1944 (17th)
##  8 Amy Adams                 3     0 2005 (78th) 2010 (83rd)
##  9 Amy Irving                1     0 1983 (56th) 1983 (56th)
## 10 Amy Madigan               1     0 1985 (58th) 1985 (58th)
## # ℹ 419 more rows
 # Assuming your dataset is named "actress"
actresses_with_two_or_more_wins <- actress %>%
  filter(Wins >= 2)

# Count the number of actresses with two or more wins
count_actresses_with_two_or_more_wins <- nrow(actresses_with_two_or_more_wins)

# Display the result
print(count_actresses_with_two_or_more_wins)
## [1] 18
  # Assuming your dataset is named "actress"
actresses_five_or_more_nominations_no_wins <- actress %>%
  filter(Nominations >= 5, Wins == 0)

# Display the rows for actresses with five or more nominations but no wins
print(actresses_five_or_more_nominations_no_wins)
## # A tibble: 4 × 5
##   Nominee       Nominations  Wins First_Year    Last_Year  
##   <chr>               <int> <int> <chr>         <chr>      
## 1 Deborah Kerr            6     0 1949 (22nd)   1960 (33rd)
## 2 Glenn Close             5     0 1982 (55th)   1988 (61st)
## 3 Irene Dunne             5     0 1930/31 (4th) 1948 (21st)
## 4 Thelma Ritter           6     0 1950 (23rd)   1962 (35th)