mydata <- data.frame(y = c(1, 2, 3, 4), x1 = c(2.5, 2.3, 2.2, 1.2), x2 = c(2.3, 2.3, 9.3, 2.4))
> mydata
y x1 x2
1 1 2.5 2.3
2 2 2.3 2.3
3 3 2.2 9.3
4 4 1.2 2.4
I would like to remove the column y
from mydata
. So I use the following command:
> mydata[, -which(names(mydata) %in% c("y"))]
x1 x2
1 2.5 2.3
2 2.3 2.3
3 2.2 9.3
4 1.2 2.4
However, if I only have 2 columns, then using the above command results in a vector:
mydata2 <- data.frame(y = c(1, 2, 3, 4), x1 = c(2.5, 2.3, 2.2, 1.2))
> mydata2[, -which(names(mydata2) %in% c("y"))]
[1] 2.5 2.3 2.2 1.2
Instead, I would like the output to be:
x1
1 2.5
2 2.3
3 2.2
4 1.2
How do I remove the y
column by name and keep the result in a data.frame format with the original column name?