Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

r
dataframe
columns
communitycreator

How to access the columns of a data frame in R

Onyejiaku Theophilus Chidalu

Overview

In this shot, we are going to briefly look at different ways we can access the items of a data frame in R. A data frame represents data displayed in a table format. A data frame contains different types of data and represents these in rows and columns, like a table.

Accessing the columns of a data frame

The column items in a data frame in R can be accessed using:

  1. Single brackets [], which would display them as a column.
  2. Double brackets [[]], which would display them as a list.
  3. Dollar symbol , which would display them as a list.

Example 1: Using single brackets []

# creating a data frame
My_Data_Frame <- data.frame (
  Height = c("Tall", "Average", "short"),
  Body_structure = c("Meso", "Endo", "Ecto"),
  Age = c(35, 30, 45)
)


# accessing the first column of the data frame
My_Data_Frame[1]

# accessing the second column of the data frame 
My_Data_Frame[2]

Accessing the column of a data frame using single brackets

Code explanation

  • Line 2: We create a variable My_Data_Frame, which represents a data frame object with 3 columns, using the data.frame() function.

  • Line 10: We access the first column of the data frame by referring to its index number (1) or position in the data frame using single brackets[].

  • Line 13: We access the second column of the data frame by referring to its index number (2) or position in the data frame using single brackets [].

Example 2: Using double brackets [[]]

# creating a data frame
My_Data_Frame <- data.frame (
  Height = c("Tall", "Average", "short"),
  Body_structure = c("Meso", "Endo", "Ecto"),
  Age = c(35, 30, 45)
)

# accessing the first column of the data frame
My_Data_Frame[["Height"]]
Accessing the column items of a data frame using double brackets

Code explanation

This is similar to the previous example, except that we use double brackets [[]] to access the first column of the data frame.

Example 3: using the dollar symbol

# creating a data frame
My_Data_Frame <- data.frame (
  Height = c("Tall", "Average", "short"),
  Body_structure = c("Meso", "Endo", "Ecto"),
  Age = c(35, 30, 45)
)

# accessing the first column of the data frame
My_Data_Frame$Height
Accessing the column items of a data frame using $

Code explanation

This is similar to the previous examples except that we use the symbol, right after the data frame variable My_Data_Frame and before the name of the column, to access the first column of the data frame.

RELATED TAGS

r
dataframe
columns
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring