0

I am trying to get the mean of the first five elements in a column within a dataframe using the summarize function from the dplyr package. Right now, I am able to get the mean of the entire column but I want to restrict the mean() function to only calculate the first five values in the column.

  mean_5_films <- summarize(
    genre_df,
    average = mean(vote_average, na.rm = TRUE)
  )

Image of dataframe for reference: enter image description here

Mana
  • 97
  • 1
  • 14
  • It's easier to help you and test possible solutions if you post a minimal [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Pictures of data aren't helpful because we can't copy/paste the data into R – MrFlick Feb 12 '20 at 20:13

2 Answers2

3

How about

mean_5_films <- summarize(
  genre_df,
  average = mean(head(vote_average,5), na.rm = TRUE)
)

That will take the first 5 vote_average valsues or you could use slice

mean_5_films <- genre_df %>%
  slice(1:5 %>% 
  summarize(average = mean(vote_average, na.rm = TRUE))
MrFlick
  • 195,160
  • 17
  • 277
  • 295
0

Another option:

mean_5_films <- summarize(
  genre_df,
  average = mean(vote_average[1:5], na.rm = TRUE)
)
arg0naut91
  • 14,574
  • 2
  • 17
  • 38