Please help using R to answer this question.
The question is to write a simpler version of the given code without loops that computes the same output without storing it to an object. The output should be identical to the output object shown.
HINT: THE COMPUTATION CAN BE DONE WITH A SINGLE COMMAND
The iris data in the datasets package is a famous data set that gives the measurements (in centimeters) of the variables sepal length, sepal width, petal length, and petal width, respectively, for 50 flowers from each of 3 species of iris. The species are Iris setosa, versicolor, and virginica.
Consider the following working code and output:
> str(iris) 'data.frame': 150 obs. of 5 variables: $ Sepal.Length: num 5.1 4.9 4.7 4.6 5.0 $ Sepal.Width : num 3.5 3.0 3.2 3.1 3.6 $ Petal.Length: num 1.4 1.4 1.3 1.5 1.4 $ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 $ Species : Factor w/ 3 levels "setosa","versicolor","virginica"
numeric_vars <- colnames(iris)[1:4]
> numeric_vars
output <- matrix(NA, nrow = nlevels(iris$Species), ncol = length(numeric_vars)) rownames(output) <- levels(iris$Species) colnames(output) <- numeric_vars for (i in seq_along(levels(iris$Species))) { for (j in seq_along(numeric_vars)) { output[i, j] <- mean(iris[iris$Species == levels(iris$Species)[i], numeric_vars[j]]) } }
> output
Sepal.Length Sepal.Width Petal.Length Petal.Width setosa 5.006 3.428 1.462 0.246 versicolor 5.936 2.770 4.260 1.326 virginica 6.588 2.974 5.552 2.026