1. By using the select()
function of the dplyr package of the tidyverse collection. The name of each column to delete is passed in with a minus sign before it:
df <- select(df, -col_1, -col_3)
Powered By
If, instead, we have too many columns to delete, it makes more sense to keep the rest of the columns rather than delete the columns in interest. In this case, the syntax is similar, but the names of the columns to keep aren’t preceded with a minus sign:
df <- select(df, col_2, col_4)
Powered By
2. By using the built-in subset() function of the base R. If we need to delete only one column, we assign to the select parameter of the function the column name preceded with a minus sign. To delete more than one column, we assign to this parameter a vector containing the necessary column names preceded with a minus sign:
df <- subset(df, select=-col_1)
df <- subset(df, select=-c(col_1, col_3))
Powered By
If, instead, we have too many columns to delete, it makes more sense to keep the rest of the columns rather than delete the columns in interest. In this case, the syntax is similar, but no minus sign is added:
df <- subset(df, select=col_2)
df <- subset(df, select=c(col_2, col_4))
Leave a Reply