Open In App

Select DataFrame Column Using Character Vector in R

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to select dataframe columns using character vectors in R programming language.

Data frame in use:

To extract columns using character we have to use colnames() function and the index of the column to select is given with it using []. The approach is sort of the same as extracting a column from dataframe except instead of $, [] is used.

Syntax:

dataframe[ , colnames(dataframe)[column_number]]

Here,

  • dataframe is the input dataframe
  • colnames function gives the column names
  • column number is a vector that takes column number with an index

Example: R program to select dataframe columns using character vector

R




# create a dataframe with 3 columns and 4 rows
data=data.frame(id=c(1,2,3,4),
                name=c('manoj','deepu','ramya','manoja'),
                marks=c(100,89,90,81))
  
# display column1
print(data[ , colnames(data)[1]]  )
  
# display column2
print(data[ , colnames(data)[2]]  )
  
# display column3
print(data[ , colnames(data)[3]]  )


Output:

[1] 1 2 3 4

[1] “manoj”  “deepu”  “ramya”  “manoja”

[1] 100  89  90  81

Example 2:R program to select dataframe columns using character vector

R




# create a dataframe with 4 columns and 5 rows
data=data.frame(id=c(1,2,3,4,5), 
                name=c('manoj','deepu','ramya','manoja','sravya'),
                marks=c(100,89,90,81,90),
                address=c('hyd','pune','chennai','banglore','chennai'))
  
# display column1
print(data[ , colnames(data)[1]]  )
  
# display column2
print(data[ , colnames(data)[2]]  )
  
# display column3
print(data[ , colnames(data)[3]]  )
  
# display column4
print(data[ , colnames(data)[4]]  )


Output:

[1] 1 2 3 4 5

[1] “manoj”  “deepu”  “ramya”  “manoja” “sravya”

[1] 100  89  90  81  90

[1] “hyd”      “pune”     “chennai”  “banglore” “chennai”



Last Updated : 23 Sep, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads