I need to select the levels of Species in the dataset Iris (available in R) with the function subset() and calculate the mean of the column Petal.Length from the same dataset, everything with a for loop. I know that I can do this calculations with the function tappy, but the task consists in using a for loop.
I tried writing a vector in which I would put the results:
medie <- rep(NA,3)
names(medie) <- levels(iris$Species)
and then this as the loop:
for (i in 1:length(medie)){
medie[i] <- mean(subset(iris, Species==levels(Species))$Petal.Length)
}
but this are the results I get:
> medie
setosa versicolor virginica
3.796 3.796 3.796
Any help?