Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Key elements of the visualization process
Environment - the R Language
17. Creating a data frame

Instruction

We know how to save many values of one type in one variable, but what if we want to save many different types values in one place? For example, suppose you want to save your family members' age, gender, name, and marital status? Then you need a data frame. You can think of data frame as the R version of a table, with columns and rows. A data frame looks like this:

  name sex age marital_status
1 Anne   F  23           TRUE
2 Jeff   M  42          FALSE
3 Carl   M  24           TRUE

This data frame has three rows and four columns. To create it, you would write:

family <- data.frame(
  name = c("Anne", "Jeff", "Carl"), 
  sex = factor(c("F", "M", "M"), levels=c("F", "M")), 
  age = c(23,42,24), marital_status = c(T, F, T) )

Note that we are using the data.frame() function. The arguments within the function act as columns. For example:

name = c("Anne", "Jeff", "Carl")

Here we define the name of the column as name. After the equals sign, you use a character vector to add values for the three observations in the column: c("Anne", "Jeff", "Carl").

Exercise

Create a data frame about zoo animals. Give it three rows and three columns (name, age, category). Create the columns from these vectors:

c("Suzanne", "Freddy", "Bo"), c(2,4,5), c("birds", "mammals","mammals")

The last vector should be defined as a factor with the levels c("mammals", "birds", "others").

Save this data frame as the zooDataset variable. When you're done, press the Run and Check Code button to check your code.

Stuck? Here's a hint!

You should write:

zooDataset <- data.frame(
  name = c("Suzanne", "Freddy", "Bo"),
  age = c(2,4,5),
  category = factor(
    c("birds", "mammals","mammals"), 
    levels = c("mammals", "birds", "others"))
)