Select Columns by Index Using dplyr

Select Columns by Index Using dplyr, To pick data frame columns by index position in dplyr, use the following basic syntax.

Columns in specified index places can be selected.

df %>%
  select(1,2, 4)

Columns in particular index positions are excluded.

df %>%
  select(-c(1,2))

Select Columns by Index Using dplyr

With the following data frame, the following examples demonstrate how to use this syntax in practice.

LSTM Network in R » Recurrent Neural network » finnstats

Let’s create a data frame

df <- data.frame(team=c('Q1', 'Q2', 'Q3', 'Q4', 'Q5'),
                 points=c(9, 2, 3, 6, 9),
                 kick=c(13, 18, 31, 32, 14),
                 pass=c(32, 22, 23, 34, 35),
                 blocks=c(25, 39, 24, 28, 55))

Now we can view the data frame

df
team points kick pass blocks
1   Q1      9   13   32     25
2   Q2      2   18   22     39
3   Q3      3   31   23     24
4   Q4      6   32   34     28
5   Q5      9   14   35     55

Example 1: Columns in specified index places can be selected

The code below demonstrates how to choose columns in specified index positions.

How to Calculate the Scalar Product in R » finnstats

library(dplyr)

select columns in positions 1, 3, and 4

df %>%
  select(1, 3, 4)
  team kick pass
1   Q1   13   32
2   Q2   18   22
3   Q3   31   23
4   Q4   32   34
5   Q5   14   35

Example 2: Select Columns in Range

The code below demonstrates how to select columns from a range.

rbind in r-Combine Vectors, Matrix or Data Frames by Rows » finnstats

library(dplyr)

Now we can select columns in positions 2 through 3

df %>%
  select(2:3)
  points kick
1      9   13
2      2   18
3      3   31
4      6   32
5      9   14

Example 3: Exclude Specific Columns

The code below demonstrates how to omit specific columns depending on their index position.

library(dplyr)

select all columns except those in positions 1 and 2.

How to Calculate Jaccard Similarity in R » finnstats

df %>%
  select(-c(1, 2))
  kick pass blocks
1   13   32     25
2   18   22     39
3   31   23     24
4   32   34     28
5   14   35     55

The first and second columns are not included.

Have you found this article to be interesting? I’d be glad if you could forward it to a friend or share it on Twitter or Linked In to help it spread.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

five × 3 =