Before you start, enter the following code:
data <- mtcars
Solutions are available here.
Exercise 1
Use logical operators to output only those rows of data
where column mpg
is between 15 and 20 (excluding 15 and 20).
Exercise 2
Use logical operators to output only those rows of data
where column cyl
is equal to 6 and column am
is not 0.
Exercise 3
Use logical operators to output only those rows of data
where column gear
or carb
has the value 4.
Exercise 4
Use logical operators to output only the even rows of data
.
Exercise 5
Use logical operators and change every fourth element in column mpg
to 0.
Exercise 6
Output only those rows of data
where columns vs
and am
have the same value 1, solve this without using ==
operator.
Exercise 7
(TRUE + TRUE) * FALSE
, what does this expression evaluate to and why?
Exercise 8
Output only those rows of data
where at least vs
or am
have the value 1, solve this without using ==
or !=
.
Exercise 9
Explain the difference between |
, ||
, &
and &&
.
Exercise 10
Change all values that are 0 in the column am
in data
to 2.
Exercise 11
Add 2 to every element in the column vs
without using numbers.
Exercise 12
Output only those rows of data
where vs
and am
have different values, solve this without using ==
or !=
.
the answer to question 12 is wrong. It only produces true if one argument in the xor() equates to 1, and the other to 0. It returns false for the case where one argument is 2 and another is 1, which goes against what the question is asking.
Good point. We are changing the data in previous exercises so it’s good to reload original data before solving this one. (write and run “data <- mtcars" before writing the argument)
I am not clear on Q6.
Why does that solution work?
Also, what does data[data$am, ] and data[data$am] mean?
0=FALSE
1 or above =TRUE
so
if data$am is greater then 0, its true
if data$vs is greater then 0, its true.
TRUE & TRUE results in TRUE