Anandapadmanathan
Anandapadmanathan

Reputation: 355

Error in generating mean using tapply function

Hi I've tried to generate mean of Petal.Width and Sepal.Width of each species from iris dataset.

However i'm getting error.

code

tapply(iris$Species, iris$Petal.Width, mean)

which result in 0.1 0.2 0.3 0.4 0.5 0.6 1 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2 2.1 2.2 2.3 2.4 2.5 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA There were 22 warnings (use warnings() to see them)

tapply(iris$Species, iris$Sepal.Length , mean) 

which result in 4.3 4.4 4.5 4.6 4.7 4.8 4.9 5 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9 6 6.1 6.2 6.3 6.4 6.5 NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA 6.6 6.7 6.8 6.9 7 7.1 7.2 7.3 7.4 7.6 7.7 7.9 NA NA NA NA NA NA NA NA NA NA NA NA There were 35 warnings (use warnings() to see them)

Upvotes: 0

Views: 213

Answers (2)

Tony Ladson
Tony Ladson

Reputation: 3649

A tidyverse approach

library(tidyverse)

iris %>% 
  group_by(Species) %>% 
  summarise_at(.vars = c('Sepal.Length', 'Sepal.Width', 'Petal.Length', 'Petal.Width'), .funs = mean)

# A tibble: 3 x 5
#  Species    Sepal.Length Sepal.Width Petal.Length Petal.Width
#  <fct>             <dbl>       <dbl>        <dbl>       <dbl>
#1 setosa             5.01        3.43         1.46       0.246
#2 versicolor         5.94        2.77         4.26       1.33 
#3 virginica          6.59        2.97         5.55       2.03 

Upvotes: 1

Khaynes
Khaynes

Reputation: 1986

Your arguments are the wrong way around ...

tapply(iris$Petal.Width, iris$Species, mean)
#    setosa versicolor  virginica 
#     0.246      1.326      2.026 

tapply(iris$Sepal.Length, iris$Species, mean)
#     setosa versicolor  virginica 
#     5.006      5.936      6.588

Have you considered a data.table approach though?

library(data.table)
iris <- data.table(iris)

# Calculate the mean for all columns by Species ...
iris[, lapply(.SD, mean, na.rm = TRUE), Species]
#      Species Sepal.Length Sepal.Width Petal.Length Petal.Width
# 1:     setosa        5.006       3.428        1.462       0.246
# 2: versicolor        5.936       2.770        4.260       1.326
# 3:  virginica        6.588       2.974        5.552       2.026

Upvotes: 1

Related Questions