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
data= data.frame (id= c (1,2,3,4),
name= c ( 'manoj' , 'deepu' , 'ramya' , 'manoja' ),
marks= c (100,89,90,81))
print (data[ , colnames (data)[1]] )
print (data[ , colnames (data)[2]] )
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
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' ))
print (data[ , colnames (data)[1]] )
print (data[ , colnames (data)[2]] )
print (data[ , colnames (data)[3]] )
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”
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
23 Sep, 2021
Like Article
Save Article