library(png)
Image by Gordon Johnson from Pixabay

Image by Gordon Johnson from Pixabay

Data Import

  1. Download flag.csv and flag.names to your working directory. Make sure to set your working directory appropriately!

  2. Let’s look at some information about this file. Open flag.names in RStudio by double clicking it in the files pane in bottom left. Read through this file.

  1. Import the flag.csv data into R. Store it in a data.frame named flag_df.
library(readr)
flag_df <- read_csv("C:/Users/Mitcheyla$/Desktop/DATA 101, Fall Semester/flag.csv")
## New names:
## Rows: 194 Columns: 31
## ── Column specification
## ──────────────────────────────────────────────────────── Delimiter: "," chr
## (4): name, mainhue, topleft, botright dbl (27): ...1, landmass, zone, area,
## population, language, religion, bars, ...
## ℹ 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.
## • `` -> `...1`
View(flag_df)
  1. Check to make sure the class of flag_df is data.frame. Then find the dimensions of flag_df.
is.data.frame(flag_df)
## [1] TRUE
dim(flag_df)
## [1] 194  31
  1. Print out the first 5 lines and the last 5 lines of flag_df.
head(flag_df, 5)
## # A tibble: 5 × 31
##    ...1 name   landm…¹  zone  area popul…² langu…³ relig…⁴  bars stripes colours
##   <dbl> <chr>    <dbl> <dbl> <dbl>   <dbl>   <dbl>   <dbl> <dbl>   <dbl>   <dbl>
## 1     1 Afgha…       5     1   648      16      10       2     0       3       5
## 2     2 Alban…       3     1    29       3       6       6     0       0       3
## 3     3 Alger…       4     1  2388      20       8       2     2       0       3
## 4     4 Ameri…       6     3     0       0       1       1     0       0       5
## 5     5 Andor…       3     1     0       0       6       0     3       0       3
## # … with 20 more variables: red <dbl>, green <dbl>, blue <dbl>, gold <dbl>,
## #   white <dbl>, black <dbl>, orange <dbl>, mainhue <chr>, circles <dbl>,
## #   crosses <dbl>, saltires <dbl>, quarters <dbl>, sunstars <dbl>,
## #   crescent <dbl>, triangle <dbl>, icon <dbl>, animate <dbl>, text <dbl>,
## #   topleft <chr>, botright <chr>, and abbreviated variable names ¹​landmass,
## #   ²​population, ³​language, ⁴​religion
tail(flag_df, 5)
## # A tibble: 5 × 31
##    ...1 name   landm…¹  zone  area popul…² langu…³ relig…⁴  bars stripes colours
##   <dbl> <chr>    <dbl> <dbl> <dbl>   <dbl>   <dbl>   <dbl> <dbl>   <dbl>   <dbl>
## 1   190 Weste…       6     3     3       0       1       1     0       0       3
## 2   191 Yugos…       3     1   256      22       6       6     0       3       4
## 3   192 Zaire        4     2   905      28      10       5     0       0       4
## 4   193 Zambia       4     2   753       6      10       5     3       0       4
## 5   194 Zimba…       4     2   391       8      10       5     0       7       5
## # … with 20 more variables: red <dbl>, green <dbl>, blue <dbl>, gold <dbl>,
## #   white <dbl>, black <dbl>, orange <dbl>, mainhue <chr>, circles <dbl>,
## #   crosses <dbl>, saltires <dbl>, quarters <dbl>, sunstars <dbl>,
## #   crescent <dbl>, triangle <dbl>, icon <dbl>, animate <dbl>, text <dbl>,
## #   topleft <chr>, botright <chr>, and abbreviated variable names ¹​landmass,
## #   ²​population, ³​language, ⁴​religion
  1. Print out the summary statistics of each variable of flag_df.
summary(flag_df)
##       ...1            name              landmass          zone      
##  Min.   :  1.00   Length:194         Min.   :1.000   Min.   :1.000  
##  1st Qu.: 49.25   Class :character   1st Qu.:3.000   1st Qu.:1.000  
##  Median : 97.50   Mode  :character   Median :4.000   Median :2.000  
##  Mean   : 97.50                      Mean   :3.572   Mean   :2.211  
##  3rd Qu.:145.75                      3rd Qu.:5.000   3rd Qu.:4.000  
##  Max.   :194.00                      Max.   :6.000   Max.   :4.000  
##       area           population         language        religion    
##  Min.   :    0.0   Min.   :   0.00   Min.   : 1.00   Min.   :0.000  
##  1st Qu.:    9.0   1st Qu.:   0.00   1st Qu.: 2.00   1st Qu.:1.000  
##  Median :  111.0   Median :   4.00   Median : 6.00   Median :1.000  
##  Mean   :  700.0   Mean   :  23.27   Mean   : 5.34   Mean   :2.191  
##  3rd Qu.:  471.2   3rd Qu.:  14.00   3rd Qu.: 9.00   3rd Qu.:4.000  
##  Max.   :22402.0   Max.   :1008.00   Max.   :10.00   Max.   :7.000  
##       bars           stripes          colours           red        
##  Min.   :0.0000   Min.   : 0.000   Min.   :1.000   Min.   :0.0000  
##  1st Qu.:0.0000   1st Qu.: 0.000   1st Qu.:3.000   1st Qu.:1.0000  
##  Median :0.0000   Median : 0.000   Median :3.000   Median :1.0000  
##  Mean   :0.4536   Mean   : 1.552   Mean   :3.464   Mean   :0.7887  
##  3rd Qu.:0.0000   3rd Qu.: 3.000   3rd Qu.:4.000   3rd Qu.:1.0000  
##  Max.   :5.0000   Max.   :14.000   Max.   :8.000   Max.   :1.0000  
##      green             blue             gold            white       
##  Min.   :0.0000   Min.   :0.0000   Min.   :0.0000   Min.   :0.0000  
##  1st Qu.:0.0000   1st Qu.:0.0000   1st Qu.:0.0000   1st Qu.:1.0000  
##  Median :0.0000   Median :1.0000   Median :0.0000   Median :1.0000  
##  Mean   :0.4691   Mean   :0.5103   Mean   :0.4691   Mean   :0.7526  
##  3rd Qu.:1.0000   3rd Qu.:1.0000   3rd Qu.:1.0000   3rd Qu.:1.0000  
##  Max.   :1.0000   Max.   :1.0000   Max.   :1.0000   Max.   :1.0000  
##      black           orange        mainhue             circles      
##  Min.   :0.000   Min.   :0.000   Length:194         Min.   :0.0000  
##  1st Qu.:0.000   1st Qu.:0.000   Class :character   1st Qu.:0.0000  
##  Median :0.000   Median :0.000   Mode  :character   Median :0.0000  
##  Mean   :0.268   Mean   :0.134                      Mean   :0.1701  
##  3rd Qu.:1.000   3rd Qu.:0.000                      3rd Qu.:0.0000  
##  Max.   :1.000   Max.   :1.000                      Max.   :4.0000  
##     crosses          saltires          quarters         sunstars     
##  Min.   :0.0000   Min.   :0.00000   Min.   :0.0000   Min.   : 0.000  
##  1st Qu.:0.0000   1st Qu.:0.00000   1st Qu.:0.0000   1st Qu.: 0.000  
##  Median :0.0000   Median :0.00000   Median :0.0000   Median : 0.000  
##  Mean   :0.1495   Mean   :0.09278   Mean   :0.1495   Mean   : 1.387  
##  3rd Qu.:0.0000   3rd Qu.:0.00000   3rd Qu.:0.0000   3rd Qu.: 1.000  
##  Max.   :2.0000   Max.   :1.00000   Max.   :4.0000   Max.   :50.000  
##     crescent         triangle           icon           animate     
##  Min.   :0.0000   Min.   :0.0000   Min.   :0.0000   Min.   :0.000  
##  1st Qu.:0.0000   1st Qu.:0.0000   1st Qu.:0.0000   1st Qu.:0.000  
##  Median :0.0000   Median :0.0000   Median :0.0000   Median :0.000  
##  Mean   :0.0567   Mean   :0.1392   Mean   :0.2526   Mean   :0.201  
##  3rd Qu.:0.0000   3rd Qu.:0.0000   3rd Qu.:0.7500   3rd Qu.:0.000  
##  Max.   :1.0000   Max.   :1.0000   Max.   :1.0000   Max.   :1.000  
##       text           topleft            botright        
##  Min.   :0.00000   Length:194         Length:194        
##  1st Qu.:0.00000   Class :character   Class :character  
##  Median :0.00000   Mode  :character   Mode  :character  
##  Mean   :0.08247                                        
##  3rd Qu.:0.00000                                        
##  Max.   :1.00000
  1. Print out the structure of flag_df.
str(flag_df)
## spec_tbl_df [194 × 31] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
##  $ ...1      : num [1:194] 1 2 3 4 5 6 7 8 9 10 ...
##  $ name      : chr [1:194] "Afghanistan" "Albania" "Algeria" "American-Samoa" ...
##  $ landmass  : num [1:194] 5 3 4 6 3 4 1 1 2 2 ...
##  $ zone      : num [1:194] 1 1 1 3 1 2 4 4 3 3 ...
##  $ area      : num [1:194] 648 29 2388 0 0 ...
##  $ population: num [1:194] 16 3 20 0 0 7 0 0 28 28 ...
##  $ language  : num [1:194] 10 6 8 1 6 10 1 1 2 2 ...
##  $ religion  : num [1:194] 2 6 2 1 0 5 1 1 0 0 ...
##  $ bars      : num [1:194] 0 0 2 0 3 0 0 0 0 0 ...
##  $ stripes   : num [1:194] 3 0 0 0 0 2 1 1 3 3 ...
##  $ colours   : num [1:194] 5 3 3 5 3 3 3 5 2 3 ...
##  $ red       : num [1:194] 1 1 1 1 1 1 0 1 0 0 ...
##  $ green     : num [1:194] 1 0 1 0 0 0 0 0 0 0 ...
##  $ blue      : num [1:194] 0 0 0 1 1 0 1 1 1 1 ...
##  $ gold      : num [1:194] 1 1 0 1 1 1 0 1 0 1 ...
##  $ white     : num [1:194] 1 0 1 1 0 0 1 1 1 1 ...
##  $ black     : num [1:194] 1 1 0 0 0 1 0 1 0 0 ...
##  $ orange    : num [1:194] 0 0 0 1 0 0 1 0 0 0 ...
##  $ mainhue   : chr [1:194] "green" "red" "green" "blue" ...
##  $ circles   : num [1:194] 0 0 0 0 0 0 0 0 0 0 ...
##  $ crosses   : num [1:194] 0 0 0 0 0 0 0 0 0 0 ...
##  $ saltires  : num [1:194] 0 0 0 0 0 0 0 0 0 0 ...
##  $ quarters  : num [1:194] 0 0 0 0 0 0 0 0 0 0 ...
##  $ sunstars  : num [1:194] 1 1 1 0 0 1 0 1 0 1 ...
##  $ crescent  : num [1:194] 0 0 1 0 0 0 0 0 0 0 ...
##  $ triangle  : num [1:194] 0 0 0 1 0 0 0 1 0 0 ...
##  $ icon      : num [1:194] 1 0 0 1 0 1 0 0 0 0 ...
##  $ animate   : num [1:194] 0 1 0 1 0 0 1 0 0 0 ...
##  $ text      : num [1:194] 0 0 0 0 0 0 0 0 0 0 ...
##  $ topleft   : chr [1:194] "black" "red" "green" "blue" ...
##  $ botright  : chr [1:194] "green" "red" "white" "red" ...
##  - attr(*, "spec")=
##   .. cols(
##   ..   ...1 = col_double(),
##   ..   name = col_character(),
##   ..   landmass = col_double(),
##   ..   zone = col_double(),
##   ..   area = col_double(),
##   ..   population = col_double(),
##   ..   language = col_double(),
##   ..   religion = col_double(),
##   ..   bars = col_double(),
##   ..   stripes = col_double(),
##   ..   colours = col_double(),
##   ..   red = col_double(),
##   ..   green = col_double(),
##   ..   blue = col_double(),
##   ..   gold = col_double(),
##   ..   white = col_double(),
##   ..   black = col_double(),
##   ..   orange = col_double(),
##   ..   mainhue = col_character(),
##   ..   circles = col_double(),
##   ..   crosses = col_double(),
##   ..   saltires = col_double(),
##   ..   quarters = col_double(),
##   ..   sunstars = col_double(),
##   ..   crescent = col_double(),
##   ..   triangle = col_double(),
##   ..   icon = col_double(),
##   ..   animate = col_double(),
##   ..   text = col_double(),
##   ..   topleft = col_character(),
##   ..   botright = col_character()
##   .. )
##  - attr(*, "problems")=<externalptr>

Data Cleaning/Management

We are going to use the dplyr package.

  1. Load the tidyverse and convert the type of flag_df to tibble.
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
## ✔ ggplot2 3.3.6      ✔ dplyr   1.0.10
## ✔ tibble  3.1.8      ✔ stringr 1.4.1 
## ✔ tidyr   1.2.1      ✔ forcats 0.5.2 
## ✔ purrr   0.3.5      
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
flag_df <- as_tibble(flag_df)
  1. Find the variable (column) names of flag_df.
colnames(flag_df)
##  [1] "...1"       "name"       "landmass"   "zone"       "area"      
##  [6] "population" "language"   "religion"   "bars"       "stripes"   
## [11] "colours"    "red"        "green"      "blue"       "gold"      
## [16] "white"      "black"      "orange"     "mainhue"    "circles"   
## [21] "crosses"    "saltires"   "quarters"   "sunstars"   "crescent"  
## [26] "triangle"   "icon"       "animate"    "text"       "topleft"   
## [31] "botright"

Something should look strange about the first column name. Let’s investigate this.

  1. Print out the first column.
flag_df[,1]
## # A tibble: 194 × 1
##     ...1
##    <dbl>
##  1     1
##  2     2
##  3     3
##  4     4
##  5     5
##  6     6
##  7     7
##  8     8
##  9     9
## 10    10
## # … with 184 more rows
  1. Delete the first column of flag_df.
flag_df <- subset(flag_df, select = -1 )
  1. Verify that there are no missing values in flag_df.
sum(is.na(flag_df))
## [1] 0

At this point, we know there are no missing values in the dataset so we will use dplyr to make the dataset a bit more readable to us. Look at the flag.names file again. Under “Attribute Information” look at the variables landmass, zone, language, religion.

Instead of encoding these categories using numbers, we would like to just use the categories in the variables. For example, in the zone column, we want our data to be “NE”, “SE”, “SW”, “NW”, instead of 1, 2, 3, 4.

  1. Change each of the columns landmass, zone, language, and religion to hold their actual categorical data (not their encoded numbers). The type of each of these columns should be Factor.
flag_df$landmass<-as.character(flag_df$landmass)
flag_df$landmass[flag_df$landmass == "1"]<- "N.America" 
flag_df$landmass[flag_df$landmass == "2"]<- "S.America" 
flag_df$landmass[flag_df$landmass == "3"]<- "Europe" 
flag_df$landmass[flag_df$landmass == "4"]<- "Africa" 
flag_df$landmass[flag_df$landmass == "5"]<- "Asia" 
flag_df$landmass[flag_df$landmass == "6"]<- "Oceania" 


flag_df$zone<-as.character(flag_df$zone)
flag_df$zone[flag_df$zone == "1"]<- "NE" 
flag_df$zone[flag_df$zone == "2"]<- "SE" 
flag_df$zone[flag_df$zone == "3"]<- "SW" 
flag_df$zone[flag_df$zone == "4"]<- "NW" 


flag_df$language<-as.character(flag_df$language)
flag_df$language[flag_df$language == "1"]<- "English"
flag_df$language[flag_df$language == "2"]<- "Spanish" 
flag_df$language[flag_df$language == "3"]<- "French" 
flag_df$language[flag_df$language == "4"]<- "German" 
flag_df$language[flag_df$language == "5"]<- "Slavic"
flag_df$language[flag_df$language == "6"]<- "Other Indo-European" 
flag_df$language[flag_df$language == "7"]<- "Chinese" 
flag_df$language[flag_df$language == "8"]<- "Arabic" 
flag_df$language[flag_df$language == "9"]<- "Japanese/Turkish/Finnish/Magyar" 
flag_df$language[flag_df$language == "10"]<- "Others"


flag_df$religion<-as.character(flag_df$religion)
flag_df$religion[flag_df$religion == "0"]<- "Catholic" 
flag_df$religion[flag_df$religion == "1"]<- "Other Christian" 
flag_df$religion[flag_df$religion == "2"]<- "Muslim" 
flag_df$religion[flag_df$religion == "3"]<- "Buddhist" 
flag_df$religion[flag_df$religion == "4"]<- "Hindu" 
flag_df$religion[flag_df$religion == "5"]<- "Ethnic" 
flag_df$religion[flag_df$religion == "6"]<- "Marxist" 
flag_df$religion[flag_df$religion == "7"]<- "Others"

flag_df$landmass<-as.factor(flag_df$landmass)
flag_df$zone<-as.factor(flag_df$zone)
flag_df$language<-as.factor(flag_df$language)
flag_df$religion<-as.factor(flag_df$religion)

Notice from our earlier structure command that the data types for columns red, green, blue, gold, white, black, orange, crescent, triangle, icon, animate, text are all integer. Looking at flag.names these integer variables are really just an encoding for true (1) or false (0). We don’t want to compute with these 1s and 0s (for example find a mean). So we should change these to logicals.

  1. Change the column type to logical for the following columns: red, green, blue, gold, white, black, orange, crescent, triangle, icon, animate, and text.
flag_df$red<-as.logical(flag_df$red)
flag_df$green<-as.logical(flag_df$green)
flag_df$blue<-as.logical(flag_df$blue)
flag_df$gold<-as.logical(flag_df$gold)
flag_df$white<-as.logical(flag_df$white)
flag_df$black<-as.logical(flag_df$black)
flag_df$orange<-as.logical(flag_df$orange)
flag_df$crescent<-as.logical(flag_df$crescent)
flag_df$triangle<-as.logical(flag_df$triangle)
flag_df$icon<-as.logical(flag_df$icon)
flag_df$animate<-as.logical(flag_df$animate)
flag_df$text<-as.logical(flag_df$text)

Now that our data is clean, let’s answer some questions about it!

Data Investigation

  1. Print out how many countries have each “mainhue” category.
table(flag_df$mainhue)
## 
##  black   blue  brown   gold  green orange    red  white 
##      5     40      2     19     31      4     71     22
  1. How many countries have the three colors red, white, and blue in their flags? How many countries have ONLY the three colors red, white, and blue in their flags?
rbw_colors <- flag_df %>%
  filter(red == TRUE & blue == TRUE & white == TRUE)
nrow(rbw_colors)
## [1] 63
rbw_only <- rbw_colors %>%
  filter(red == TRUE & blue == TRUE & white == TRUE & black == FALSE & gold == FALSE & green == FALSE & orange == FALSE)
nrow(rbw_only)
## [1] 27
  1. Print out the data observations for the 10 countries with the largest populations. The 10 data observations should be printed out in descending order according to population.
arrange(flag_df,desc(population)) %>%
  head(10)
## # A tibble: 10 × 30
##    name  landm…¹ zone   area popul…² langu…³ relig…⁴  bars stripes colours red  
##    <chr> <fct>   <fct> <dbl>   <dbl> <fct>   <fct>   <dbl>   <dbl>   <dbl> <lgl>
##  1 China Asia    NE     9561    1008 Chinese Marxist     0       0       2 TRUE 
##  2 India Asia    NE     3268     684 Other … Hindu       0       3       4 FALSE
##  3 USSR  Asia    NE    22402     274 Slavic  Marxist     0       0       2 TRUE 
##  4 USA   N.Amer… NW     9363     231 English Other …     0      13       3 TRUE 
##  5 Indo… Oceania SE     1904     157 Others  Muslim      0       2       2 TRUE 
##  6 Braz… S.Amer… SW     8512     119 Other … Cathol…     0       0       4 FALSE
##  7 Japan Asia    NE      372     118 Japane… Others      0       0       2 TRUE 
##  8 Bang… Asia    NE      143      90 Other … Muslim      0       0       2 TRUE 
##  9 Paki… Asia    NE      804      84 Other … Muslim      1       0       2 FALSE
## 10 Mexi… N.Amer… NW     1973      77 Spanish Cathol…     3       0       4 TRUE 
## # … with 19 more variables: green <lgl>, blue <lgl>, gold <lgl>, white <lgl>,
## #   black <lgl>, orange <lgl>, mainhue <chr>, circles <dbl>, crosses <dbl>,
## #   saltires <dbl>, quarters <dbl>, sunstars <dbl>, crescent <lgl>,
## #   triangle <lgl>, icon <lgl>, animate <lgl>, text <lgl>, topleft <chr>,
## #   botright <chr>, and abbreviated variable names ¹​landmass, ²​population,
## #   ³​language, ⁴​religion

Let’s see if we can find any patterns in the data.

  1. Group the flags by landmass and find the following for each group:

Your output should be a data frame with each row corresponding to a group. There will be five columns.

Repeat this process except group by zone, language, and religion.

# You may find this function useful (ie. you should call this function in your code)!  It calculates the mode of a factor.

cat_mode <- function(cat_var){
  mode_idx <- which.max(table(cat_var))
  levels(cat_var)[mode_idx]
}



flag_df %>%
  group_by(landmass) %>%
  summarise(ModeMainhue=cat_mode(mainhue),Median=median(sunstars),animateLandmass=sum(animate), LandmassPercent=animateLandmass/(length(animate))*100)
## # A tibble: 6 × 4
##   landmass  Median animateLandmass LandmassPercent
##   <fct>      <dbl>           <int>           <dbl>
## 1 Africa       0                 7            13.5
## 2 Asia         1                 6            15.4
## 3 Europe       0                 4            11.4
## 4 N.America    0                13            41.9
## 5 Oceania      2.5               6            30  
## 6 S.America    0                 3            17.6
flag_df %>%
  group_by(zone) %>%
  summarise(ModeZone=cat_mode(mainhue),Median=median(sunstars),animateZone=sum(animate), ZonePercent=animateZone/(length(animate))*100)
## # A tibble: 4 × 4
##   zone  Median animateZone ZonePercent
##   <fct>  <dbl>       <int>       <dbl>
## 1 NE         0          14        15.4
## 2 NW         0          15        25.9
## 3 SE         0           7        24.1
## 4 SW         1           3        18.8
flag_df %>%
  group_by(language) %>%
  summarise(ModeLang=cat_mode(mainhue),Median=median(sunstars),animateLang=sum(animate), LanguagePercent=animateLang/(length(animate))*100)
## # A tibble: 10 × 4
##    language                        Median animateLang LanguagePercent
##    <fct>                            <dbl>       <int>           <dbl>
##  1 Arabic                             0             2            10.5
##  2 Chinese                            3             1            25  
##  3 English                            0            18            41.9
##  4 French                             0             0             0  
##  5 German                             0             0             0  
##  6 Japanese/Turkish/Finnish/Magyar    0.5           0             0  
##  7 Other Indo-European                0             5            16.7
##  8 Others                             0             9            19.6
##  9 Slavic                             0.5           1            25  
## 10 Spanish                            0             3            14.3
flag_df %>%
  group_by(religion) %>%
  summarise(ModeReligion=cat_mode(mainhue),Median=median(sunstars),animateReligion=sum(animate), Percent=animateReligion/(length(animate))*100)
## # A tibble: 8 × 4
##   religion        Median animateReligion Percent
##   <fct>            <dbl>           <int>   <dbl>
## 1 Buddhist             0               4   50   
## 2 Catholic             0               4   10   
## 3 Ethnic               0               6   22.2 
## 4 Hindu                0               0    0   
## 5 Marxist              1               3   20   
## 6 Muslim               0               3    8.33
## 7 Other Christian      0              19   31.7 
## 8 Others               1               0    0

Do you see any patterns in flag mainhue, sun or star symbols, and animate images? If so, describe these patterns. (Hint: you should see patterns! Look at the trends when grouping by landmass, zone, language, and religion.) Write a paragraph to answer this question.

When grouping by landmass, zone, language and religion, we can see N.America, NW, English language and Other Christian have the highest number of flags with animate images