0

I want a mean vector of the iris dataset such that the first element in the vector is the mean of the first column, the second is the mean of the second column etc..

My code is:

data("iris")

mean(iris[,1:4])

I get the message:

Warning message:
In mean.default(iris[, 1:4]) :
  argument is not numeric or logical: returning NA

If I try to calculate the mean of each collumn with mean(iris[,1]), mean(iris[,2])... I have no problem but if I do the mean(iris[,1:4]) it returns NA

s_baldur
  • 29,441
  • 4
  • 36
  • 69
MtSet
  • 27
  • 3
  • 1
    `sapply(iris[,1:4], mean)` – s_baldur Jan 10 '22 at 12:56
  • Does this answer your question? [Grouping functions (tapply, by, aggregate) and the \*apply family](https://stackoverflow.com/questions/3505701/grouping-functions-tapply-by-aggregate-and-the-apply-family) – AlexB Jan 10 '22 at 13:05
  • Answered at https://stackoverflow.com/questions/30941504/calculate-mean-for-multiple-columns-in-data-frame – jakekraska Jan 10 '22 at 13:06

1 Answers1

1

You need to use colMeans to get the mean values for each column/list (a data.frame is a set of lists). mean only works on single vectors.

colMeans(iris[,1:4])
Sepal.Length  Sepal.Width Petal.Length  Petal.Width 
    5.843333     3.057333     3.758000     1.199333
Andre Wildberg
  • 12,344
  • 3
  • 12
  • 29