DS4PS / cpp-526-sum-2021

Coure shell for CPP 526.
https://ds4ps.org/cpp-526-sum-2021/
MIT License
1 stars 3 forks source link

Lab 06: Does mutate add columns to the dataframe? #45

Open mtwelker opened 3 years ago

mtwelker commented 3 years ago

I thought the "mutate" function would add a column to the dataframe. But in Lab 06, the team.budget and cost.p.win columns that I create in step 3 seem to disappear by step 4. Here's what I did:

# Step 2: Join Salaries & Teams
dat.comb <- Salaries %>% 
  left_join(Teams, by = c("teamID", "yearID"))
# Step 3: Calculate Cost per Win
dat.comb %>% 
  group_by(yearID, teamID)  %>% 
  mutate(team.budget = sum(salary.adj), cost.p.win = team.budget / W / 100000 ) %>% 
  select(yearID, teamID, team.budget, W, cost.p.win)

Which produces: image

Then when I move on to Step 4, team.budget and cost.p.win have disappeared. (Even though I don't have any other commands between step 3 and step 4.) If I run this:

# Step 4: Select, Filter, & Arrange
dat.comb %>% 
  group_by(yearID, teamID)  %>% 
  select(yearID, teamID, lgID=lgID.x, Rank, G, W, team.budget, cost.p.win)

I get the error: "Error: Can't subset coluns that don't exist. X Column 'team.budget' doesn't exist...." Same thing if I comment out team.budget, except it says "X Column 'cost.p.win' doesn't exist.

Am I misunderstanding how mutate works? Or am I using it wrong? If I add the mutate command back into step 4, it works:

dat.comb %>% 
  group_by(yearID, teamID)  %>% 
  mutate(team.budget = sum(salary.adj), cost.p.win = team.budget / W / 100000 ) %>% 
  select(yearID, teamID, lgID=lgID.x, Rank, G, W, team.budget, cost.p.win)

image (Yes, I know it's returning too many lines for each team, which is the next thing I'll try to figure out.)

But if I created team.budget and cost.p.win with mutate in step 3, shouldn't I be able to just use them in step 4 without having to create them again? What am I missing? Thanks for any clarification you can offer!

lecy commented 3 years ago

You arent assigning changes anywhere. Compare Step 2 and Step 3. Throw but no catch!

mtwelker commented 3 years ago

Oh! I think I see what you're saying. I guess I thought mutate did that automatically. This makes more sense, though. Thank you!