DataFrame Rows & Column Segment in R

The process of extracting the row and column information in a dataset by simply using the index or slice operator is known as Slicing.

In R Programming, the rows and columns can be sliced in two ways either by using an index or using the name of the row and column. The slice operator is much more useful when one wants to extract if the index or name of the row or column is known. Slicing the data frame using the slice operator is more efficient than slicing the data set using the slice() method in the dplyr package.

Syntax: dataframe[start_row:end_row,start_column:end_column]

Loading Dataset

Load the default dataset iris in R and convert it as a data frame.

R




# Load the iris dataset
data(iris)
  
# Convert the data set to data frame
df <- data.frame(iris)


Examples 

Let’s see some examples of slicing for the above dataset.

Slice the data frame in such a way that only 3rd row data is extracted.

R




# To extract all the columns of row number 3 records
df[3,]


Output:

 

Slice the data frame to extract all the columns from row number 5 to 10.

R




# To extract all the columns from row number 5 to 10
df[5:10,]


Output:

 

Slice the data frame to extract 5th column and all the rows.

R




# To extract 5th column and all the rows of it
df[,5]


Output:

 

Slice the data frame to extract the 3rd and 5th column data present from 2nd to 5th row.

R




# To extract the 3rd and 5th column
# data present from 2nd to 5th row
df[2:5,3:5]


Output: