wiscostret / fplscrapR

This package enables those interested in Fantasy Premier League to perform detailed data analysis of the game, using the FPL's JSON API. The fplscrapR functions help R users collect and parse data from the Official Fantasy Premier League website.
Creative Commons Zero v1.0 Universal
76 stars 16 forks source link

Can't get function to work with current season data #13

Closed WobblyOG closed 3 years ago

WobblyOG commented 4 years ago

Hello, I'm trying to create a function that takes a vector of player names as an input and outputs a dataframe of their week by week scores using get_player_info(). The function works if I specify season = 18 but I can't get it to work for the current season.

Here's the code that works: fn = function(team){ df <- data.frame(matrix(ncol = 0, nrow = 38)) for(i in team){ points = get_player_details(name = i, season = 18)$total_points df[,i] = points } return(df) }

df1 = fn(team)

but removing season = 18 and changing nrow to 29 (29 gameweeks) gives me this error:

Error in [<-.data.frame(*tmp*, , i, value = c(0L, 1L, 0L, 1L, 3L, : replacement has 28 rows, data has 29

I'm new to R and I can't quite figure out why. Any help would be appreciated! Thanks :)

wiscostret commented 4 years ago

Hi, sorry for getting to this so late, I missed it. There will be some variance in how many games different players have played, so you don´t want to restrict your matrix to a specific number of rows.

Your solution is also a bit too complex - there´s no need to loop, so here´s an alternative that should work:

# define the players you want to get data on. Can do this manually as here, or through a function
players = c("Virgil van Dijk", "Andrew Robertson", "Trent Alexander-Arnold")

# grab the player IDs using the get_player_id() function
playerids = get_player_id(players)

# grab the player details
df = get_player_details(playerids$id)

# select the total_points column.
df$total_points

# or if you want a data frame with player names, round and gameweek score (requires dplyr):
df %>% select(playername,round,total_points)

Again sorry for the slow reply. Hope this is still helpful.

wiscostret commented 3 years ago

Closing - resolved.