R Data Frames

A data frame is a table or a two-dimensional array like structure in which each column contains values of one variable (means the first column can be a character, the second column can be numeric and thirds column can be logical, etc.) and each row has one set of values from each column. Let’s see some characteristics of the data frame:

  • Name of the column should be non-empty.
  • Name of the row should be unique.
  • The data stored in the data frame can be a factor, numeric or character type.
  • Each column must contain the same number of data items.

Creating a Data Frame

To create a data frame we have to use data.frame() function.

Output:

Get the Structure of Data Frame

We can get the structure of the data frame by using the str() function.

Example:

Output:

Summary of Data in Data Frame

We can obtain the nature and summary of data by applying the summary() function.

Example:

Output:

Access Specific Column from a Data Frame

We can extract a specific column from a data frame using the column name.

Example 1:

Let’s see an example to extract the name and marks of student from the student data frame:

Output:

Example 2:

Let’s see an example to access only first two rows with all columns:

Output:

Example 3:

Let’s see an example to extract 1st and 4th row with 2nd and 4th 3rd column:

Output:

Modify a Data Frame

We can modify the data frame by using reassignment.

Example:

Output:

Adding Rows to a Data Frame

We can add the rows to the data frame using the rbind() function.

Example 1:

Output:

We can use rbind() in another different way. In the below example we create a data frame with new rows and merge it with the existing data frame to create the final data frame:

Example 2:

Output:

Adding Columns to a Data Frame

We can add the rows to the data frame using the cbind() function.

Example 1:

Output:

Since data frames are implemented as a list; we can also add new columns through simple list-like assignments.

Example 2:

Output:

Deleting columns and Rows from a Data Frame

We can delete the data frame columns by assigning NULL to it.

Example:

Output:

Reference:
https://www.rdocumentation.org/packages/base/versions/3.5.3/topics/data.frame