53
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