We use $ and [] to get specific columns from a table of data. This helps us look at or change just the part we want.
Accessing columns ($, []) in 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.
df$age
df["age"]df[["age"]]df[2]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.
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)
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.
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.