Alex
Alex

Reputation: 353

Selecting columns of dataset without using the number of the column but the name of the column

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

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388797

  1. 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.

  2. = 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

Related Questions