0
0
R Programmingprogramming~5 mins

Accessing columns ($, []) in R Programming

Choose your learning style9 modes available
Introduction

We use $ and [] to get specific columns from a table of data. This helps us look at or change just the part we want.

You want to see just one column from a table of data.
You need to change values in a specific column.
You want to use a column's data in a calculation.
You want to add a new column or remove one.
You want to check the values inside a column.
Syntax
R Programming
dataframe$column_name

dataframe["column_name"]

dataframe[["column_name"]]

The $ sign is used to pick a column by name directly.

The [] brackets can select columns by name or position, but using double brackets [[ ]] returns the column as a vector.

Examples
This gets the column named 'age' from the dataframe df using $.
R Programming
df$age
This gets the column 'age' as a one-column dataframe using single brackets.
R Programming
df["age"]
This gets the column 'age' as a vector using double brackets.
R Programming
df[["age"]]
This gets the second column of df as a one-column dataframe.
R Programming
df[2]
Sample Program

This program creates a small table with names and ages. It shows three ways to get the 'age' column: with $, with single [], and with double [[]]. It prints each result so you can see the difference.

R Programming
df <- data.frame(name = c("Anna", "Ben", "Cara"), age = c(25, 30, 22))

# Access age column using $
age_vector <- df$age
print(age_vector)

# Access age column using single []
age_df <- df["age"]
print(age_df)

# Access age column using double [[]]
age_vector2 <- df[["age"]]
print(age_vector2)
OutputSuccess
Important Notes

Using $ is simple but only works with column names that are valid variable names (no spaces or special characters).

Using [] with column names returns a dataframe, which keeps the column as a table.

Using [[]] returns the column as a simple vector, which is useful for calculations.

Summary

Use $ to quickly get a column by name as a vector.

Use [] with a column name to get a one-column dataframe.

Use [[]] to get a column as a vector when you want to work with its values directly.