Homework 1 — SOLUTIONS

Task 0

Finish practice examples 1. For yourself. (They won’t be graded.)

Task 1

Write a function which defines whether a number is prime. You can presume that your function will take an integer as argument. (Hint: the %% operator gives the remainder after division. So 5 %% 3 = 2 and 5 %% 5 = 0.)

is_prime <- function(x) {
    is_prime = TRUE
    if (x > 2) {
        for (i in 2:(x-1)) {
            if (x %% i == 0) {
                is_prime = FALSE
            }
        }
    }
    return(is_prime)
}

Task 2

Write a function which takes a non-negative numeric vector and returns back a 0-1 vector according to the followings: zero elements should stay zero and positive elements should be transformed to one. Call this function as dummify. For example, if a <- c(0, 34, 2) then the dummify(a) should return c(0, 1, 1). (You can assume that the function will only get vectors with non-negative elements.)

dummify <- function(x) {
    as.numeric(x > 0)
}

Task 3

In Data directory you find a trade.zip folder. Download and extract it to a directory in your machine. You are going to find 11 csv files there which contain trade data from World Bank from different years. Load and bind them together following the steps below:

  1. Load the file.
  2. Create a year variable which takes the value of that year.
  3. Bind this file to the rest.

Hint: You can achive this with a for loop by looping over the years.

trade_files <- "/home/divenyijanos/Dropbox/teaching/Programming_Tools/Fall2015/Data/trade/"
for (year in 2003:2013) {
    if (year == 2003) {
        total <- read.csv(paste0(trade_files, year, ".csv"))
    } else {
        total <- rbind(total, read.csv(paste0(trade_files, year, ".csv")))
    }
}
## Warning in file(file, "rt"): cannot open file '/home/divenyijanos/Dropbox/
## teaching/Programming_Tools/Fall2015/Data/trade/2003.csv': No such file or
## directory
## Error in file(file, "rt"): cannot open the connection
str(total)
## Error in str(total): object 'total' not found
# Change numbers stored as characters into numbers stored as numbers
total[c("Exports", "General.Imports", "Consumption.Imports")] <- sapply(
    total[c("Exports", "General.Imports", "Consumption.Imports")],
    as.numeric
)
## Error in lapply(X = X, FUN = FUN, ...): object 'total' not found
# dplyr solution
library(dplyr)
total <- total %>%
    mutate_each(funs(as.numeric), matches("ports"))
## Error in eval(lhs, parent, parent): object 'total' not found
str(total)
## Error in str(total): object 'total' not found