Method Using Numeric Indexing

Numeric indexing in R can be used to access a single or multiple rows from the data frame. The rows to be accessed can be specified in the square brackets using row indices of the data frame. 

dataframe[i,] where i is the row number of the data frame 

R




# creating a data frame
data_frame = data.frame(col1 = c(1:15),
                        col2 = letters[1:15],
                        col3 = c(0,1,1,1,0,0,0,0,
                                 0,1,1,0,1,1,0))
print("Data Frame")
print(data_frame)
  
# accessing a particular row from
# data frame
data_frame4 <- data_frame[4,]
print("Row 4 of data frame")
print(data_frame4)


Output

[1] "Data Frame"
   col1 col2 col3
1     1    a    0
2     2    b    1
3     3    c    1
4     4    d    1
5     5    e    0
6     6    f    0
7     7    g    0
8     8    h    0
9     9    i    0
10   10    j    1
11   11    k    1
12   12    l    0
13   13    m    1
14   14    n    1
15   15    o    0
[1] "Row 4 of data frame"
  col1 col2 col3
4    4    d    1

Multiple rows of the data frame can also be accessed in the data frame by specifying the row number in the vector and them using them in the square brackets. 

R




# creating a data frame
data_frame = data.frame(col1 = c(1:15),
                        col2 = letters[1:15],
                        col3 = c(0,1,1,1,0,0,0,
                                 0,0,1,1,0,1,1,0))
print("Data Frame")
print(data_frame)
  
# specifying multiple rows of the
# data frame
row_vec <- c(1,3,5)
  
# accessing the rows of the data frame
data_frame_mul <- data_frame[row_vec,]
print("Multiple rows of data frame")
print(data_frame_mul)


Output

[1] "Data Frame"
   col1 col2 col3
1     1    a    0
2     2    b    1
3     3    c    1
4     4    d    1
5     5    e    0
6     6    f    0
7     7    g    0
8     8    h    0
9     9    i    0
10   10    j    1
11   11    k    1
12   12    l    0
13   13    m    1
14   14    n    1
15   15    o    0
[1] "Multiple rows of data frame"
  col1 col2 col3
1    1    a    0
3    3    c    1
5    5    e    0

DataFrame Row Slice in R

In this article, we are going to see how to Slice row in Dataframe using R Programming Language.

Row slicing in R is a way to access the data frame rows and further use them for operations or methods. The rows can be accessed in any possible order and stored in other vectors or matrices as well. Row slicing is an important operation which is easily supported by R programming language. 

Similar Reads

There are various ways to slice data frame rows in R :

Using Numeric Indexing Using Name Indexing Indexing using logical vectors...

Method 1. Using Numeric Indexing

Numeric indexing in R can be used to access a single or multiple rows from the data frame. The rows to be accessed can be specified in the square brackets using row indices of the data frame....

Method 2. Using Name Indexing

...

Method 3. Indexing using logical vectors

...

Contact Us