Browsing resource, all submissions are temporary.
a. Suppose I create a vector x <- 1:120. Then I decide to set all values in 'x' greater than 78 to 0. I write the following code, but get a warning message and it doesn't do anything to 'x'. What is wrong with the code?
x <- 1:120
if(x > 78) { x <- 0 }
b. Suppose I want to calculate the value of 1 + 1/2 + 1/3 + ··· + 1/100. I write the following code, but it doesn't seem to work. What's wrong with the code? (try to figure out the answer without running the code first)
x <- 0 i <- 1 while(i <= 100) { x <- x + 1/i }
c. In the following code, what will be returned by the last command?
x <- c(1,5,10,10,5,1) y <- c(10,5,1) x == y
d. Suppose x is an integer vector of length 366. Each element in x is an integer between 1 and 365. Consider the following code:
x
for (n in 2:366) { if (any(x[1:(n-1)]==x[n])) { break } } print(n)
What does this code do? It counts the total number of elements in 'x', i.e. n is the same as length(x). It counts the number of repeated numbers in 'x'. It searches for the first occurance of a repeated number in 'x'. It generates a random number and stores it in 'n'. None of the above.
Hint: If you find it hard to figure out, try assigning x to some specific values and run the code. For example, try x <- c(1:365,34) and x <- c(rep(1:7,52),105,218) and see what you'll get. Which of the answers above seem to match the outputs? Once you identify a possible correct answer, try running the code with x <- sample.int(365, 366, replace=TRUE), which draws 366 integers randomly between 1 and 365 with replacement and assigns them to x. Is the result consistent with the possible correct answer?
x <- c(1:365,34)
x <- c(rep(1:7,52),105,218)
x <- sample.int(365, 366, replace=TRUE)