Getting Odd Rows from the Data Frame
The number of rows in a data frame in R can be fetched by the nrow() method. It returns the number of rows in the data frame. The seq_len() method is then applied to generate the integers beginning with 1 to the number of rows. The modulo method with the integer 2 in R can be used to fetch the odd or even rows based on their indexes on the obtained vector. The corresponding row indices of the data frame are operated with a modulo method. The following syntax is used to fetch the odd rows of the data frame.
Syntax:
seq_len(rows)%%2
Data frame indexing method can then be used to obtain rows where the odd row index is equivalent to 1.
Syntax:
data_frame[odd_row == 1, ]
Example: Select odd rows from dataframe
R
# creating a data frame in R data_frame <- data.frame (col1 = 1:10, col2 = letters [1:10], col3 = rep (5:9,2)) print ( "Original Dataframe" ) print (data_frame) # getting number of rows in R rows <- nrow (data_frame) # extracting odd rows odd_rows <- seq_len (rows) %% 2 # getting data from odd data frame data_mod <- data_frame[odd_rows == 1, ] print ( "odd rows of dataframe" ) print (data_mod) |
Output:
[1] "Original Dataframe" col1 col2 col3 1 1 a 5 2 2 b 6 3 3 c 7 4 4 d 8 5 5 e 9 6 6 f 5 7 7 g 6 8 8 h 7 9 9 i 8 10 10 j 9 [1] "odd rows of dataframe" col1 col2 col3 1 1 a 5 3 3 c 7 5 5 e 9 7 7 g 6 9 9 i 8
Select Odd and Even Rows and Columns from DataFrame in R
In this article, we will discuss how to select odd and even rows from a dataframe in R programming language.