<<

Data Frame

A data frame is a special list in which every object has the same size.

Create a data frame

To create a data frame, the function data.frame() can be used as shown in the examples below. The data read from a file into R are often saved into a data frame.

> a <- 1:3 > b <- 4:6 > d <- 7:9 > y <- data.frame(a,b,d) > y a b d 1 1 4 7 2 2 5 8 3 3 6 9 >

Access the components of a data frame

The same methods for access the objects in a list can be used for a data frame. For example, y$a will access a in the data frame. The R function attach() can conveniently copy all objects in a data frame into R workspace so that they can be accessed using their names directly. To remove those objects, the function detach() can be used. Some examples are given below.

> y <- data.frame(a=1:4,b=5:8,d=9:12) > y a b d 1 1 5 9 2 2 6 10 3 3 7 11 4 4 8 12 > > y$a [1] 1 2 3 4 > > attach(y) > b [1] 5 6 7 8 > > detach(y) > b Error: object 'b' not found Execution halted