Search code examples
rdplyrtidyversetidyrspread

Error in the application of the spread to the lakers data set of the lubricated package


I am trying to analyze how many points each Lakers player scored between 2008 and 2009, presenting the result per year, based on the dataset lakers of the lubridate package.

I'm trying the following code:

date <- lubridate :: lakers

date <- date %>%
  mutate (Year = str_sub (date, 1, 4))%>%
  filter (points> 0 & team == 'LAL')%>%
  select (Year, player, points)%>%
  group_by (Year, player)%>%
  summarise (Total_points = sum (points))%>%
  ungroup ()%>%
  spread (player, points)  

But it fails in the spread and presents the following error:

Erro: Must extract column with a single valid subscript.
x Subscript `var` has the wrong type `function`.
ℹ It must be numeric or character.

I would like to know what the problem is. I appreciate any help.


Solution

  • The only problem is that you forgot that when you summarised points you gave the name of Total_points to it. You are calling points in the last line. This error says that your varible was not found. Just correct the name of the variable in the last line:

    date <- lubridate :: lakers
    
    date <- date %>%
      mutate(Year = (str_sub(date, 1, 4))) %>%
      filter(points> 0 & team == 'LAL')%>%
      select(Year, player, points)%>%
      group_by(Year, player) %>%
      summarise(Total_points = sum(points))%>%
      ungroup()%>%
      spread(player, Total_points)