R: Remove columns from a dataframe [duplicate]

1

How can I remove columns from a dataframe without being 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
    
asked by anonymous 22.12.2015 / 17:50

3 answers

2

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

    
22.12.2015 / 17:52
5

You can do this 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 in this way is that if only one column remains, it is automatically transformed into a vector. If you do not want this behavior use the drop = F argument.

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

Another way is to use the dplyr package and the select function:

df %>% select(-z)

Or

df %>% select(-3)

You often want to delete a column without knowing its name beforehand. For example, its name is saved in a variable.

In this case you can do this:

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

If you want to delete multiple columns in this way, you can do this:

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 data.frame does not turn vector.

    
22.12.2015 / 18:28
1

There is yet another, slightly more obscure form:

df[setdiff(names(df), "z")]
    
22.12.2015 / 18:38