Frontmaniaac
Frontmaniaac

Reputation: 250

Aggregate mean in R

I am trying to view the mean values of height, grouped by eye color of the characters, that have a number in their name. I tried it with aggregate but I can't figure out the solution

sw %>%
  filter(grepl('[0-9]',name))%>%
     aggregate(height~eye_color,mean)%>%
        setNames(c("Eye color","Mean"))

Upvotes: 3

Views: 214

Answers (2)

TarJae
TarJae

Reputation: 78927

A dplyr solution:

library(dplyr)

starwars %>%
  filter(grepl('[0-9]',name)) %>% 
  group_by(eye_color) %>% 
  summarise(mean = mean(height))

Output:

  eye_color  mean
* <chr>     <dbl>
1 black        NA
2 red         131
3 red, blue    96
4 yellow      167

Upvotes: 3

akrun
akrun

Reputation: 887118

If we want to use base R (R 4.1.0)

sw |>
    subset(grepl('[0-9]', name)) |>
    {\(dat) aggregate(cbind(Mean = height) ~ eye_color, data = dat, mean)}()

-output

#  eye_color Mean
#1       red  131
#2 red, blue   96
#3    yellow  167

data

data(starwars)
sw <- starwars

Upvotes: 3

Related Questions