Home > Back-end >  change columns with while loop
change columns with while loop

Time:12-16

In the iris dataset, I want to replace the names setosa virginica and versicolor with a letter, then convert it to an A for example setosa with a while loop and put another letter A next to it.

so setosa = AA

virginica = BB

versicolor = CC

The code I tried only adds to the numbers, I need to do it to the letters

data(iris) 
head(iris) 
Burak <- iris

running_index <- 1

  while(is.numeric(iris[ , running_index])) { 
    iris[ ,running_index] <- iris[ ,running_index]   50 
    running_index <- running_index   1
  }

CodePudding user response:

Is this what you’re trying to do? I really don’t follow the logic of your while loop or how it relates to your stated goal.

new_labels <- c(setosa = "AA", virginica = "BB", versicolor = "CC")

iris$Species <- new_labels[iris$Species]

iris[c(1, 61, 121), ]
    Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1            5.1         3.5          1.4         0.2      AA
61           5.0         2.0          3.5         1.0      BB
121          6.9         3.2          5.7         2.3      CC

CodePudding user response:

you can try the simple below code without using loop

data("iris")
iris$Species<-c(rep("AA", 50), rep("BB",50),
                rep ("CC", 50))
  • Related