Name:
Andrew ID:
Collaborated with:

On this homework, you can collaborate with your classmates, but you must identify their names above, and you must submit your own homework as an knitted HTML file on Canvas, by Sunday 10pm, this week.

Reading and writing data

df = data.frame(x = 1:10, y = rnorm(10))
df = data.frame(x = c("1", "2", "3"), stringsAsFactors = FALSE)

One useful application of reading and writing data is to save progress in long-running programs. We provide the run_simulation() function below, which inputs a numeric variable initial representing the first number in the sequence, and outputs the number of iterations needed to reach 1. Modify run_simulation() to save the value of current and iter at the end of the body of the while() loop. That is, you should be saving after every iteration of the loop. Here, current is a numeric variable that represents the current number in the sequence being calculated and iter is the number of iterations this function has computed (i.e., the current length of the sequence). Use save() to write current and iter to a file associated with the value of initial (Hint: Use the string representation of initial as a suffix or prefix to the file path.) This file should be overwritten for each iteration (so that it only stores the most recent values of current and iter).

Check that run_simulation(837799) == 524 and display the contents of the associated file with load() followed by printing the current and iter.

next_simulation = function(past) {
  if (past %% 2 == 0) {
    return (past / 2)
  } else {
    return (3 * past + 1)
  }
}

run_simulation <- function(initial) {
  current = initial
  iter = 0
  while (current != 1) {
    iter = iter + 1
    current = next_simulation(current)
  }
  return(iter)
}

Reordering

Merging