15.1 C
London
Friday, July 5, 2024
HomeStatistics TutorialRHow to Select Columns by Index in R (With Examples)

How to Select Columns by Index in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the following basic syntax to select columns by index in R:

#select specific columns by index
df[ , c(1, 4)]

#select specific columns in index range
df[ , 1:3]

#exclude specific columns by index
df[ , -c(2, 5)]

The following examples show how to use this syntax in practice with the following data frame:

#create data frame
df frame(team=c('A', 'B', 'C', 'D', 'E'),
                 points=c(99, 90, 86, 88, 95),
                 assists=c(33, 28, 31, 39, 34),
                 rebounds=c(30, 28, 24, 24, 28),
                 blocks=c(7, 7, 5, 9, 13))

#view data frame
df

  team points assists rebounds blocks
1    A     99      33       30      7
2    B     90      28       28      7
3    C     86      31       24      5
4    D     88      39       24      9
5    E     95      34       28     13

Example 1: Select Columns by Index

The following code shows how to select specific columns by index:

#select columns in 1st and 4th position
df[ , c(1, 4)]

  team rebounds
1    A       30
2    B       28
3    C       24
4    D       24
5    E       28

Example 2: Select Columns in Index Range

The following code shows how to select specific columns in an index range:

#select columns in positions 1 through 3
df[ , 1:3]

  team points assists
1    A     99      33
2    B     90      28
3    C     86      31
4    D     88      39
5    E     95      34

Example 3: Exclude Columns by Index

The following code shows how to exclude specific columns by index:

#select all columns except columns in positions 2 and 5
df[ , -c(2, 5)]

  team assists rebounds
1    A      33       30
2    B      28       28
3    C      31       24
4    D      39       24
5    E      34       28

Notice that this returns all of the columns in the data frame except for the columns in index positions 2 and 5.

Additional Resources

The following tutorials explain how to perform other common operations on data frame columns in R:

How to Drop Columns from Data Frame in R
How to Switch Two Columns in R
How to Combine Two Columns into One in R

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories