# one input, and several output in simple data structure:
factors=function(number){
# empty vector that will collect output
vectorOfAnswers=c(1 )
# for every value in the sequence...
for (i in 2: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
}
factors(30)
## [1] 1 2 3 5 6 10 15 30
This function accepted an integer number and returned its factors. Please answer these questions:
The function will execute n number of times depending on n input.
By including 1 in vector of answers and changing the value to sequence to 2:number, the for section will now execute n-1 times depending on n input value used.
setwd("C:/Users/leoto/OneDrive/Documents/598/Week 4/session4")
library(rio)
fileName='demo_hdi.csv'
hdi.dat=import(fileName)
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(pander)
tapply(hdi.dat$hdi, hdi.dat$demType, max)
## Authoritarian Flawed democracy Full democracy Hybrid regime
## 0.863 0.933 0.953 0.814
hdi.dat %>% group_by( demType ) %>% summarize(max(hdi))
## # A tibble: 4 x 2
## demType `max(hdi)`
## <chr> <dbl>
## 1 Authoritarian 0.863
## 2 Flawed democracy 0.933
## 3 Full democracy 0.953
## 4 Hybrid regime 0.814
hdi.dat %>% filter(hdi==0.933 | hdi==0.814 | hdi==0.953 | hdi==0.863)
## country demType demScore hdi
## 1 Hong Kong Flawed democracy 6.15 0.933
## 2 Montenegro Hybrid regime 5.74 0.814
## 3 Norway Full democracy 9.87 0.953
## 4 Sweden Full democracy 9.39 0.933
## 5 United Arab Emirates Authoritarian 2.76 0.863
tophdi <- c(.863,.933,.953,.814)
hdi.dat[hdi.dat$hdi %in% tophdi,]
## 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
dat2 <- hdi.dat %>% select(-demScore, -country)
tapply(X=dat2$hdi, INDEX = list(dat2$demType), FUN = max)
## Authoritarian Flawed democracy Full democracy Hybrid regime
## 0.863 0.933 0.953 0.814
dat2 %>% group_by(demType) %>% summarize(max(hdi))
## # A tibble: 4 x 2
## demType `max(hdi)`
## <chr> <dbl>
## 1 Authoritarian 0.863
## 2 Flawed democracy 0.933
## 3 Full democracy 0.953
## 4 Hybrid regime 0.814
library(reshape2, warn.conflicts = FALSE)
hdi_L1 = melt(hdi.dat)
## Using country, demType as id variables
head(hdi_L1)
## country demType variable value
## 1 Afghanistan Authoritarian demScore 2.97
## 2 Albania Hybrid regime demScore 5.98
## 3 Algeria Authoritarian demScore 3.50
## 4 Angola Authoritarian demScore 3.62
## 5 Argentina Flawed democracy demScore 7.02
## 6 Armenia Hybrid regime demScore 4.79