...

/

Data Frames and Lists in R

Data Frames and Lists in R

Get introduced to data frames and lists in R.

We’ll dive a little deeper and look at two of the most important objects in R: data frames and lists.

Data frame

A data frame is probably the most useful and widely used of the objects discussed in this course. If we can understand vectors, then we can also understand data frames. All vectors in a data frame must have the same length, but the data in those vectors must be different modes. For now, let’s create a data frame from scratch, which also provides an opportunity to introduce some useful essential functions. Let’s make a vector of values named values and a vector of names that’s named treatment. We have two treatments, each with 20 individuals, and the average value of whatever we have measured is 5 for one group and 10 for the other group. In the code below, we have nested several functions to achieve what we want to do:

R
# First, make a vector of names for the groups
treatment<-rep(c('Group.A','Group.B'), each=20)
# Next, make a vector of hypothetical values for each group
values<-c(rnorm(20,5,1),rnorm(20,10,1))
# Combine the two vectors into a data frame
df1<-data.frame(treatment,values)
df1

In the code block given above, we see the following:

  • In line 2, we use the c() function to concatenate the words Group.A and Group.B into a single vector. Then, we use the rep() function to repeat each value in that vector 20 times. What happens if you replace the argument each= with times= ...