Indexing the Data Frame

To access the particular data in the Data Frame use square brackets and specify the column name or row numbers, and column numbers to fetch. Let’s look into the syntaxes of different ways of indexing a data frame.

# fetching the data in particular column
data["columnName"]

# fetching data of specified rows and 
# columns
data[ fromRow : toRow , columnNumber]

# fetches first row to third row 
# and second column
Eg:- data[1:3,2]  

Example:

In the below code we created a data frame and performed indexing on it by fetching the data in the specified rows and particular columns.

R




# create a data frame 
stats <- data.frame(player=c('A', 'B', 'C', 'D'),
                runs=c(100, 200, 408, NA),
                wickets=c(17, 20, NA, 5))
  
print("stats Dataframe")
stats
  
# fetch data in certain column
stats["player"]
print("----------")
  
# fetch certain rows and columns
stats[1:3,2]


Output

"stats Dataframe"
  player runs wickets
1      A  100      17
2      B  200      20
3      C  408      NA
4      D   NA       5
----------
  player
1      A
2      B
3      C
4      D
----------
100 200 408

How to create, index and modify Data Frame in R?

In this article, we will discuss how to create a Data frame, index, and modify the data frame in the R programming language.

Similar Reads

Creating a Data Frame:

A Data Frame is a two-dimensional labeled data structure. It may consist of fields/columns of different types. It simply looks like a table in SQL or like an excel worksheet. In R, to create a Data Frame use data.frame() method. The syntax to  create a data frame is given as-...

Indexing the Data Frame:

...

Modify the Data Frame:

To access the particular data in the Data Frame use square brackets and specify the column name or row numbers, and column numbers to fetch. Let’s look into the syntaxes of different ways of indexing a data frame....

Contact Us