remove columns from dataframe r code example

Example 1: drop columns by index r

#drop columns by index
df <- mydata[ -c(1,3:4) ]
#drop columns by name
df = subset(mydata, select = -c(x,z))

Example 2: r data frame remove column

df$columnName <- NULL

Example 3: drop a column in r data frame

df <- df %>%
  select(-column_to_drop)

Example 4: remove column from matrix r

# Remove third column - by column number
MyMatrix <- MyMatrix[,-3]

# Remove third and fifth columns - by feeding the matrix a boolean vector
MyMatrix <- MyMatrix[,c(TRUE,TRUE,FALSE,TRUE,FALSE,TRUE)]

Example 5: R drop columns

undesired <- c('mpg', 'cyl', 'hp')

mtcars <- mtcars %>%
  select(-one_of(undesired))

Example 6: r drop column by name

R> subset(df, select=-c(z,u))
  x y
1 1 2
2 2 3
3 3 4
4 4 5
5 5 6

Tags: