A: Remove columns from a dataframe

Asked

Viewed 1,888 times

1

How can I remove columns from a dataframe other than as follows?

> df
  x y z
1 1 6 A
2 1 5 B
3 2 4 C
4 2 3 D
5 3 2 E
6 3 1 F
> df <- data.frame(df[,1:2])
> df
  x y
1 1 6
2 1 5
3 2 4
4 2 3
5 3 2
6 3 1

3 answers

5

You can do so too:

df[, -3]

Negative indices exclude columns in R.

If you want to delete more than one column, do so:

df[,-c(1,3)]

The problem with this is that if there is only one column left it is automatically transformed into an array. If you don’t want this behavior use the argument drop = F.

df[,-c(1,3), drop = F]

Another way is by using the package dplyr and the function select:

df %>% select(-z)

Or

df %>% select(-3)

Often you want to delete a column without knowing its name previously. For example its name is saved in a variable.

In this case you can do so:

nome_col <- "z"
df[[nome_col]] <- NULL

If you want to delete several columns this way, you can do so:

nomes_col <- c("z", "x")
df[ , -which(names(df) %in% nomes_col), drop = F]

In this case, I use the argument drop = F so that the data.frame do not vector.

2


The most practical form is as follows: df$z <- NULL.

1

There is still another way, a little more obscure:

df[setdiff(names(df), "z")]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.