1

I am trying to make my code display the mean attendance of a specified country in a new column. When I run the code below (Should be an image) I get the table also listed in the image. Can anyone explain how to display only the column of the specified country name and the mean attendance in the new column and explain what I am doing wrong? Thank you

My_Code

EDIT: sorry I'm obviously new at this, my code is

WorldCupMatches %>%   
  select(Home.Team.Name, Attendance) %>% 
  group_by(Home.Team.Name == "USA") %>% 
  mutate(AVG_Attendance = mean(Attendance, na.rm = T))

so to explain more, worldcupmatches is a dataframe and it has columns named "home.team.names" and "Attendance." I am trying to add a column by mutating and I want the mutated column to show the mean attendance for a country. The country i am looking for in this particular situation is USA. I also want the output to only display the columns "home.team.name" (with the USA as the home team), attendance and the mutated column that would be the mean attendance.

Thank you all for the help i got a lot of great answers!

  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Do not share code or data as an image because we can't easily run that ourselves. If you want to limit records use the `filter()` dplyr verb rather than trying to filter in the `group_by` verb, – MrFlick Apr 20 '21 at 17:10
  • 1
    Looks like you want `filter` instead of `group_by` and `summarise` instead of `mutate`. – Jon Spring Apr 20 '21 at 17:17

2 Answers2

0

First group by Home.Team.Name

Then you get the mean of each country in the table with summarise

If you just want USA then add filter(Home.Team.Name == "USA") at the end

WorldCupMatches %>% 
  select(Home.Team.Name, Attendance) %>% 
  group_by(Home.Team.Name) %>% 
  summarise(AVG_Attendance = mean(Attendance, na.rm = T)) %>% 
  filter(Home.Team.Name == "USA")

TarJae
  • 72,363
  • 6
  • 19
  • 66
0

If you want to have averages by group just group_byand summarise:

library(dplyr)
df %>%
  group_by(Hometeam) %>%
  summarise(mean = mean(Attendance))
# A tibble: 3 x 2
  Hometeam  mean
* <chr>    <dbl>
1 France    555 
2 UK        500.
3 USA       373 

If you're just interested in a specific group you can filter that group:

df %>%
  filter(Hometeam=="USA") %>%
  summarise(mean = mean(Attendance))
  mean
1  373

Data:

df <- data.frame(
  Hometeam = c("USA", "UK", "USA", "France", "UK", "USA"),
  Attendance = c(120, 333, 222, 555, 666, 777)
)
Chris Ruehlemann
  • 20,321
  • 4
  • 12
  • 34