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

Browsing resource, all submissions are temporary.


Logic and Subsetting

Using a logical vector to subset another vector is a very useful technique in R. This problem is designed to help you understand how this technique works. Some of the questions may be hard to figure out. The best method to find out the answers is to assign the variables to specific numbers, try out different commands, and see which one works and then figure out why it works. Learning a computer language is like learning a sport or a musical instrument. You learn it by playing it.

a. Suppose x is a numeric vector of length 3, if I type y <- (x >1 & x <10). What is stored in y?




 Tries [_1]

b. Suppose x is a numeric vector of length 5 and I type the following commands.

y <- c(TRUE,FALSE,TRUE,TRUE,FALSE)
z <- x[y]

Which of the following commands will always produce the same z? (select all that apply)
(Hint: If you have trouble figuring out the answer, try assigning x to specific numbers, e.g. x <- rnorm(5), and then try out all of the commands.)
z <- x[c(-2,-5)]
z <- x[c(2,5)]
z <- c(x[2],x[5])
z <- x[-c(2,5)]
z <- c(x[1],x[3],x[4])
z <- c(x[1],x[3:4])
z <- x[c(1,3,4)]
none of the above

 Tries [_1]

c. Continuing with the question in part (b). Which of the following commands is/are equivalent to the command x[y] <- 1? (select all that apply)
x[-c(2,5)] <- 1
c(x[1],x[3],x[4]) <- 1
c(x[2],x[5]) <- 1
x[c(1,3,4)] <- 1
c(x[1],x[3:4]) <- 1
x[c(-2,-5)] <- 1
x[c(2,5)] <- 1
none of the above

 Tries [_1]

d. Suppose x is a numeric vector of length 100, which of the following commands is equivalent to z <- x[x > 4.3 & x < 8.1]?




 Tries [_1]

e. Suppose x is a data frame with 582 rows and 10 columns. Two of the column names are foo and bar. The column in foo contains numeric values and the column in bar contains integers. Which of the following commands is equivalent to mean(x$foo[x$bar == 7])?
Hint: A similar command is used in part (e) of last week's subsetting data frame problem.





 Tries [_1]

f. Suppose x is a numeric vector of length 582. What is returned by the command mean(x > 8.1)? (Hint: Again, if you are not sure how to analyze this problem, try assigning x to specific numbers and then try out the commands. For example, set x <- rnorm(582, 8.1).)





 Tries [_1]

g. Suppose x is a logical vector of length N and there are k missing values in x. What is returned by the command mean(x,na.rm=TRUE)?





 Tries [_1]

h. Suppose x is a numeric vector of length n, and I create a new vector y by the command

n <- length(x)
y <- x[-1] - x[-n]

What is the length of the vector y? Express your answer in terms of n.

 Tries [_1]

Suppose j is an integer between 1 and length(y). Express the value of y[j] in terms of x[j] and x[j+1].

 Tries [_1]