## Introduction

These exercises are taken from the R and RStudio appendix from Modern Data Science with R: http://mdsr-book.github.io. Other materials relevant for instructors (sample activities, overview video) for this chapter can be found there.

## Typing commands

A user has typed the following commands into the console.

obj1 <- 2:10
obj2 <- c(2, 5)
obj3 <- c(TRUE, FALSE)
obj4 <- 42

What values are returned by the following commands?

obj1 * 10
obj1[2:4]
obj1[-3]
obj1 + obj2
obj1 * obj3
obj1 + obj4
obj2 + obj3
sum(obj2)
sum(obj3)

SOLUTION:

## Typing more commands

A user has typed the following commands into the console.

a <- c(10, 15)
b <- c(TRUE, FALSE)
c <- c("happy", "sad")

What do each of the following commands return? Describe the class of the object as well as its value.

data.frame(a, b, c)
cbind(a, b)
rbind(a, b)
cbind(a, b, c)
list(a, b, c)[[2]]

SOLUTION:

## Typing even more commands

A user has typed the following commands into the console.

mylist <- list(x1="sally", x2=42, x3=FALSE, x4=1:5)

What values do each of the following commands return?

is.list(mylist)
names(mylist)
length(mylist)
mylist[[2]]
mylist[["x1"]]
mylist\$x2
length(mylist[["x4"]])
class(mylist)
typeof(mylist)
class(mylist[[4]])
typeof(mylist[[3]])

SOLUTION:

## Piping

The following code undertakes some data analysis using the HELP (Health Evaluation and Linkage to Primary Care) trial.

library(mosaic)
ds <-
summarise(group_by(select(filter(mutate(ds,
sex = ifelse(female==1, "F", "M")), !is.na(pcs)), age, pcs, sex),
sex), meanage=mean(age), meanpcs=mean(pcs),n=n())

Describe in words what computations are being done. Using the ‘pipe’ notation, translate this code into a more readable version.

SOLUTION:

# solution goes here

## Concepts

The following concepts should have some meaning to you: package, function, command, argument, assignment, object, object name, data frame, named argument, quoted character string. Construct an example of R commands that make use of at least four of these. Label which part of your example R command corresponds to each.

SOLUTION:

## Names

Which of these kinds of names should be wrapped with quotation marks when used in R? 1. function name 2. file name 3. the name of an argument in a named argument 4. object name

SOLUTION:

## What’s wrong?

What’s wrong with this statement?

help(NHANES, package <- "NHANES")

## CPS

Consult the documentation for CPS85 in the mosaicData package to determine the meaning of CPS.

SOLUTION:

library(mosaicData)
# solution does here

## Errors

For each of the following assignment statements, describe the error (or note why it does not generate an error).

result1 <- sqrt 10
result2 <-- "Hello to you!"
3result <- "Hello to you"
result4 <- "Hello to you
result5 <- date()

SOLUTION: