Method Indexing using logical vectors

Data frame rows can also be subjected to a logical expression, where in the row indexes evaluating to true of the logical expression will be returned in the resulting output. 

R




# creating a data frame
data_frame = data.frame(col1 = c(1:8),
                        col2 = letters[1:8],
                        col3 = c(0,1,1,1,0,0,0,0))
  
# assigning row names 
rownames(data_frame) <- c("r1","r2","r3","r4","r5","r6")
print("Data Frame")
print(data_frame)
  
# accessing rows of data frame
# using a logical condition 
log_vec = data_frame$col3 == 0 
  
print("Dataframe where col3 values are equivalent to 0")
print(data_frame[log_vec,])


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
[1] "Dataframe where row 1 values are %2 "
  col1 col2 col3
1    1    a    0
5    5    e    0
6    6    f    0
7    7    g    0
8    8    h    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