Reputation: 353
I tried to select columns of dataset without using the index number of the column but the name of the column
data(iris)
y<-iris[, colnames = "Species"]
z<-iris[, colnames != "Species"]
Can anyone tell why line 2 & 3 are wrong
Upvotes: 0
Views: 106
Reputation: 388797
colnames
is a function, you need to call functions with ()
. colnames
needs a dataframe or matrix as input. So you need to use colnames(iris)
to get the column names of iris
dataset.
=
is an assignment operator. What you need here is comparison operator which is ==
.
y<-iris[, colnames(iris) == "Species", drop = FALSE]
z<-iris[, colnames(iris) != "Species"]
When subsetting a dataframe if the output is only of 1 column R drops its dimension and you get output as a vector. To keep data as dataframe in y
we use drop = FALSE
.
Upvotes: 1