dimanche 18 novembre 2018

For loop for substitute to numeric

I am trying, with no luck so far, to create a for loop that does the following: Change the Species, from the iris dataset, to numeric. I want to use 1 for 'setosa', 2 for 'virginica' and 3 for vericolor.

What I have is

    for(i in 1:nrow(iris)){
  if (iris$Species[i] == 'setosa') {iris$Species[i] <- (as.numeric(iris$Species[i] <- 1))}
  else if (iris$Species[i] == 'virginica' ) { iris$Species[i] <- (as.numeric(iris$Species[i] <- 2))}
  else if (iris$Species[i] == 'versicolor') { iris$Species[i] <- (as.numeric(iris$Species[i] <- 3))}
}
print(iris)

Thank you.

Aucun commentaire:

Enregistrer un commentaire