To remove only one column, I prefer the mode used by @carloscinelli
dados$x <- NULL
head(dados)
y z w
1 -0.6264538 0.4094018 0.8936737
2 0.1836433 1.6888733 -1.0472981
3 -0.8356286 1.5865884 1.9713374
4 1.5952808 -0.3309078 -0.3836321
5 0.3295078 -2.2852355 1.6541453
6 -0.8204684 2.4976616 1.5122127
As for the other cases, I prefer to use the command subset
To keep the columns x
and w
, use:
dados <- subset(dados, select = c(x, w))
head(dados)
x w
1 -0.62036668 0.8936737
2 0.04211587 -1.0472981
3 -0.91092165 1.9713374
4 0.15802877 -0.3836321
5 -0.65458464 1.6541453
6 1.76728727 1.5122127
to delete the columns x
and y
, use the sign -
before vector with column names
dados <- subset(dados, select = -c(x, y))
head(dados)
z w
1 0.4094018 0.8936737
2 1.6888733 -1.0472981
3 1.5865884 1.9713374
4 -0.3309078 -0.3836321
5 -2.2852355 1.6541453
6 2.4976616 1.5122127
It is worth an observation as to the use of the operator []
. To keep only the column w
we can use:
excluir <- c("x", "y", "z")
dados <- dados[,!(names(dados) %in% excluir)]
head(dados)
[1] 0.8936737 -1.0472981 1.9713374 -0.3836321 1.6541453 1.5122127
but in that case dados
is transformed into a vector. To correct use the parameter drop = FALSE
dados <- dados[,!(names(dados) %in% excluir), drop = FALSE]
head(dados)
w
1 0.8936737
2 -1.0472981
3 1.9713374
4 -0.3836321
5 1.6541453
6 1.5122127
or, if you prefer to use subset
dados <- subset(dados, select = c(w))
head(dados)
w
1 0.8936737
2 -1.0472981
3 1.9713374
4 -0.3836321
5 1.6541453
6 1.5122127
drop=FALSE
is magical, I spent a good few years making codes that had to adapt between date.frame/matrices and vectors...– Rcoster