Part 1

You saw this code in the session:

# one input, and several output in simple data structure:
factors=function(number){
    # empty vector that will collect output
    vectorOfAnswers=c()
    
    # for every value in the sequence...
    for (i in 1:number){
        
        #if the remainder of 'number'/'i' equals zero...
        if ((number %% i) == 0){ 
            
            # ...add 'i' to the vector of factors!
            vectorOfAnswers=c(vectorOfAnswers,i)
    }
  }
  return (vectorOfAnswers) # returning  the vector
}

This function accepted an integer number and returned its factors. Please answer these questions:

  1. For any number N, how many times does the for section is executed to compute the factos of N?

The times that the for section runs is N.

  1. Make a change in the code to reduce the times the for section is executed.

If the (i in 1:number) changes to (i in 1:number-1), the times that the for section runs decreases.

Part 2

setwd("C:/Users/xwb/Desktop/Data Analysis")
data=read.csv("session4/demo_hdi.csv")
tapply(X=data$hdi,INDEX=list(data$demType),FUN = max)
##    Authoritarian Flawed democracy   Full democracy    Hybrid regime 
##            0.863            0.933            0.953            0.814
conditions= tapply(X=data$hdi,INDEX=list(data$demType),FUN = max)
conditions
##    Authoritarian Flawed democracy   Full democracy    Hybrid regime 
##            0.863            0.933            0.953            0.814
data[data$hdi %in% conditions,]
##                  country          demType demScore   hdi
## 63             Hong Kong Flawed democracy     6.15 0.933
## 99            Montenegro    Hybrid regime     5.74 0.814
## 110               Norway   Full democracy     9.87 0.953
## 139               Sweden   Full democracy     9.39 0.933
## 152 United Arab Emirates    Authoritarian     2.76 0.863
specificrow=as.data.frame(data[data$hdi %in% conditions,])
library(reshape2)
specificrow_2<- melt(specificrow, id.vars = "country",value.name = "value")
## Warning: attributes are not identical across measure variables; they will
## be dropped
specificrow_2
##                 country variable            value
## 1             Hong Kong  demType Flawed democracy
## 2            Montenegro  demType    Hybrid regime
## 3                Norway  demType   Full democracy
## 4                Sweden  demType   Full democracy
## 5  United Arab Emirates  demType    Authoritarian
## 6             Hong Kong demScore             6.15
## 7            Montenegro demScore             5.74
## 8                Norway demScore             9.87
## 9                Sweden demScore             9.39
## 10 United Arab Emirates demScore             2.76
## 11            Hong Kong      hdi            0.933
## 12           Montenegro      hdi            0.814
## 13               Norway      hdi            0.953
## 14               Sweden      hdi            0.933
## 15 United Arab Emirates      hdi            0.863