Subset Even & Odd Rows & Columns in Data Frame R (4 Examples)

This tutorial explains how to extract odd and even rows and columns from data frame in R programming.

Example Data

data(iris)                                               # Load example data
head(iris)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 3          4.7         3.2          1.3         0.2  setosa
# 4          4.6         3.1          1.5         0.2  setosa
# 5          5.0         3.6          1.4         0.2  setosa
# 6          5.4         3.9          1.7         0.4  setosa

Example 1: Selecting Even Columns in Data Frame

iris_col_even <- iris[ , seq_len(ncol(iris)) %% 2 == 0]  # Extracting even columns
head(iris_col_even)
#   Sepal.Width Petal.Width
# 1         3.5         0.2
# 2         3.0         0.2
# 3         3.2         0.2
# 4         3.1         0.2
# 5         3.6         0.2
# 6         3.9         0.4

Example 2: Selecting Odd Columns in Data Frame

iris_col_odd <- iris[ , seq_len(ncol(iris)) %% 2 == 1]   # Extracting odd columns
head(iris_col_odd)
#   Sepal.Length Petal.Length Species
# 1          5.1          1.4  setosa
# 2          4.9          1.4  setosa
# 3          4.7          1.3  setosa
# 4          4.6          1.5  setosa
# 5          5.0          1.4  setosa
# 6          5.4          1.7  setosa

Example 3: Selecting Even Rows in Data Frame

iris_row_even <- iris[seq_len(nrow(iris)) %% 2 == 0, ]   # Extracting even rows
head(iris_row_even)
#    Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 2           4.9         3.0          1.4         0.2  setosa
# 4           4.6         3.1          1.5         0.2  setosa
# 6           5.4         3.9          1.7         0.4  setosa
# 8           5.0         3.4          1.5         0.2  setosa
# 10          4.9         3.1          1.5         0.1  setosa
# 12          4.8         3.4          1.6         0.2  setosa

Example 4: Selecting Odd Rows in Data Frame

iris_row_odd <- iris[seq_len(nrow(iris)) %% 2 == 1, ]    # Extracting odd rows
head(iris_row_odd)
#    Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1           5.1         3.5          1.4         0.2  setosa
# 3           4.7         3.2          1.3         0.2  setosa
# 5           5.0         3.6          1.4         0.2  setosa
# 7           4.6         3.4          1.4         0.3  setosa
# 9           4.4         2.9          1.4         0.2  setosa
# 11          5.4         3.7          1.5         0.2  setosa

Further Resources

In the following, you may find some further resources on topics such as variables, matrices, and extracting data:

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top