Getting Even Columns from the Data Frame

The number of columns in a data frame in R can be fetched by the ncol() method. It returns the number of columns in the data frame. The modulo method can then be used with the integer 2 in R can be used to fetch the odd or even columns based on their indexes on the obtained vector. The corresponding column 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(cols)%%2

Data frame indexing method can then be used to obtain rows where the odd column index is equivalent to 0.

Syntax:

Data_frame[, odd_cols==0 ]

Example: select even columns 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 columns in R
cols <- ncol(data_frame)
  
# extracting odd rows 
even_cols <- seq_len(cols) %% 2
  
# getting data from odd data frame
data_mod <- data_frame[, even_cols == 0]
  
print ("even columns 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] "even columns of dataframe"
 [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"


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.

Similar Reads

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....

Getting Even Rows from the Data Frame

...

Getting Odd Columns 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....

Getting Even Columns from the Data Frame

...