You can use the following methods to select all but one column in a data frame in R:
Method 1: Select All But One Column by Position
#select all but the third column
df[, -3]
Method 2: Select All But One Column by Name
#select all but column named 'this_column' df[, colnames(df)[colnames(df) != 'this_column']]
The following examples show how to use each method in practice with the following data frame in R:
#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)) #view data frame df team points assists rebounds 1 A 99 33 30 2 B 90 28 28 3 C 86 31 24 4 D 88 39 24 5 E 95 34 28
Example 1: Select All But One Column by Position
The following code shows how to select all but the column in the third position of the data frame:
#select all but the third column
df[, -3]
team points rebounds
1 A 99 30
2 B 90 28
3 C 86 24
4 D 88 24
5 E 95 28
Notice that all of the columns except the one in the third position of the data frame have been selected.
Example 2: Select All But One Column by Name
The following code shows how to select all but the column with the name ‘assists’ in the data frame:
#select all columns except the column with the name 'assists' df[, colnames(df)[colnames(df) != 'assists']] team points rebounds 1 A 99 30 2 B 90 28 3 C 86 24 4 D 88 24 5 E 95 28
Notice that all of the columns except the one with the name ‘assists’ have been selected.
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Add Column to Data Frame Based on Other Columns in R
How to Sort by Multiple Columns in R
How to Reorder Columns in R