R Program to Extract Columns From a Dataframe

There are different ways to extract columns from a data frame in R:

  • using index value
  • column name
  • using $ to access specific column

Example 1: Use Index Value to Access Dataframe Column in R

# Create a data frame
dataframe1 <- data.frame (
  Name = c("Juan", "Alcaraz", "Simantha"),
  Age = c(22, 15, 19),
  Vote = c(TRUE, FALSE, TRUE)
)

# pass index value 1 to access first column
print(dataframe1[1])

# pass index value 3 to access third column
print(dataframe1[3])

Output

     Name
1     Juan
2  Alcaraz
3 Simantha
   Vote
1  TRUE
2 FALSE
3  TRUE

In the above example, we have created a dataframe named dataframe1 with three columns Name, Age, Vote.

Here,

  • dataframe[1] - accesses all the elements of 1st column i.e. Name
  • dataframe[2] - accesses all the elements of 3rd column i.e. Vote

Example 2: Use Column Name to Access Dataframe Column in R

# Create a data frame
dataframe1 <- data.frame (
  Name = c("Juan", "Alcaraz", "Simantha"),
  Age = c(22, 15, 19),
  Vote = c(TRUE, FALSE, TRUE)
)

# access Name column
print(dataframe1[["Name"]])

# access Age column 
print(dataframe1[["Age"]])

Output

[1] "Juan"  "Alcaraz"  "Simantha"
[1] 22 15 19

In the above example, we have used the [[ ]] operator to access columns of the dataframe named dataframe1.

Here,

  • dataframe[["Name"]] - accesses all the elements of the Name column.
  • dataframe[["Age"]] - accesses all the elements of the Age column.

Example 3: Use Column Name and $ to Access Column

# Create a data frame
dataframe1 <- data.frame (
  Name = c("Juan", "Alcaraz", "Simantha"),
  Age = c(22, 15, 19),
  Vote = c(TRUE, FALSE, TRUE)
)

# access Age column
print(dataframe1$Age)

# access Vote column 
print(dataframe1$Vote)

Output

[1] 22 15 19
[1]  TRUE FALSE  TRUE

In the above example, we have used the $ operator and column name to access columns of the dataframe1 dataframe.

Here,

  • dataframe$Age - accesses all the elements of the Age column.
  • dataframe$Vote - accesses all the elements of the Vote column.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges