1. LON-CAPA Logo
  2. Help
  3. Log In
 

Browsing resource, all submissions are temporary.


The Date Class, system.time()

Use R's Date class to do the calculations in (a) and (b).

a. What is the date 1255 days after April 13, 1999?

Year     Month     Day

 Tries 0/3

b. The date of birth of a student is February 3, 1997. What is the age of this student (in days) on March 17, 2017?

Age = days

 Tries 0/5

The system.time(expression) function can be used to find out the time it takes for R to execute the expression. In the following, I create two functions f1(n) and f2(n). They both do the same calculation: find the sum of 1 + 1/2 + 1/3 + ··· + 1/n. The function f1(n) calculates the sum using a for-loop, whereas f2(n) does it by a vectorized command.

f1 <- function(n) {
     s <- 0 
     for (i in 1:n) {
        s <- s + 1/i
     }
     s
}

f2 <- function(n) {
     sum(1/(1:n))
}

Time the two functions using the commands

system.time( s1 <- f1(1e7) )
system.time( s2 <- f2(1e7) )

Note: It may take a few seconds to run the commands.

c. Are the values of s1 and s2 the same (to within 10 digits)?


 Tries 0/1

Which expression runs faster?


 Tries 0/1

d. Suppose I create 10 million random numbers following a normal distribution by the command

set.seed(8428426)
x <- rnorm(1e7)

Next, I sort x using sort(). Time the process using the command

system.time( y1 <- sort(x) )

If I want to know the smallest 10 numbers in x, I can simply type y1[1:10]. However, if I am only interested in finding the smallest 10 numbers, I can do a partial sorting. Time the following partial sorting process using the command

system.time( y2 <- sort(x,partial=1:10) )

Which of the following statements are correct? (select all that apply)
The command y2 <- sort(x,partial=1:10) runs much faster than y1 <- sort(x)
The first 10 numbers in y2 are exactly the same as the first 10 numbers in y1
The first 10 numbers in y2 are exactly the same as the last 10 numbers in y1
The last 10 numbers in y2 are exactly the same as the last 10 numbers in y1
y1 and y2 are identical

 Tries 0/3