Browsing resource, all submissions are temporary.
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 2001 2002 2003 2004 2005 2006 2007 2008 Month January February March April May June July August September October November December Day 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
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
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.
system.time(expression)
expression
f1(n)
f2(n)
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)? yes no
s1
s2
Which expression runs faster? f1(1e7) f2(1e7)
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
x
sort()
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
y1[1:10]
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
y2 <- sort(x,partial=1:10)
y1 <- sort(x)
y2
y1