<- 1
item1 <- "a"
item2 <- 3.78901 item3
P01. Introduction to R, part 1
A. Create simple objects of different types in the workspace
B. Objects with more than 1 entry are called vectors
# create some vectors using c() (short for concatenate)
# all items of a vector must be the same class
<- c("a", "b", "c")
object1 <- 1:3
object2 <- c(1.3, -4.5, 6.99)
object3
# you can create vectors using other named items or objects
<- c(item1, item2, item3)
object4
# take a look
object1
object2
object3 object4
C. Look for your objects in the environment tab (upper right)
D. What class of objects is each object?
Answer:
# use class() to find this
class(object1)
class(object2)
class(object3)
class(object4)
Is object 4 the class you expected?
Answer:
E. You can manipulate objects and make operations on them
+ 1
object2 *object3
object3/object3
object2+ object2 object1
what happened at each of these commands? is it what you expected?
Answer:
F. You can view the history of commands that were run.
check the history of commands in the history tab (upper right)
G. Make some other objects
<- data.frame(ID=1:5,
df1 animal=c("bear", "cat", "horse", "cat", "pig"),
weight=c(200, 5, 600, 8, 100))
<- matrix(data=1:50, nrow=10, ncol=5)
mat1
# view these objects
df1
mat1View(df1)
View(mat1)
In R, what is the difference between a data.frame and a matrix? hint: google it.
Answer:
H. Calculate the mean weight of the animals in df1. (i.e. mean of column 3 of df1)
# you can either refer to a column by name or by index
# check what the names are
colnames(df1)
# reference a column by name
$weight
df1
# check how to use the function "mean"
# ? allows you to view the help file of any inbuilt function
?mean
# calculate the mean
mean(df1$weight)
mean(df1[, 3])
Answer:
I. does mat1 have column names at this point?
Answer:
# set column names for mat1
colnames(mat1) <- c("A", "B", "C", "D", "E")
mat1
J. What is the value of the element row 5, column C in mat1? what is the value of row 8, column E?
# inspect the element by referencing the row, then column, either by name or number
5, "C"]
mat1[5, 3] mat1[
Answer:
K. Discard all of mat1 except the 1st and 4th column.
# subset mat1 to keep only the 1st and 4th column by number or name
c(1, 4)]
mat1[ , c("A", "D")]
mat1[ ,
# Create a new object of the smaller matrix.
# assign the subsetted version as a new object, mat2
<- mat1[ , c("A", "D")]
mat2 <- mat1[ , c(1, 4)] mat2
The solutions to this practical can be accessed here.