How to sum last n rows conditionally in R -


i have long data frame (master) this: (last row expect couldn't figure out how it)

id      match     points          team     team/points in last 3 matches 44631   154235      3          nacional    4 44623   154231      3       millonarios    3 44639   154239      1          nacional    4 44640   154239      1            junior    4 44637   154238      1       millonarios    5 44670   154260      3            junior    2 44657   154249      3          nacional    2 44668   154258      1       millonarios    7 44495   154149      0          nacional    3 44685   154263      1            junior    1 44687   154266      1          nacional    3 44688   154266      1       millonarios    6 44698   154265      3       millonarios    3 44695   154264      0            junior    1 44707   154274      1          nacional    2 44713   154273      1          nacional    1 44724   154281      3       millonarios    0  44725   154282      1            junior    0 44737   154991      1          nacional    0 

and want create new column (team/points in last 3 matches) shows cumulative sum of points every team in last 3 matches. last row of team´s match should sum points rised team in last 3 matches.

i build past cumulative sum of points every team´s match, couldn´t figure out how limit sum 3 recent matches...

this code:

>master$ptos_antes <- ave(master$points,master$teamxtourn,                     fun=function(x) cumsum(c(0, head(x,-1))) ) 

master$teamxtourn key field made subset last matches cumulative sum tournament season. master$id_team concatenated master$id_tournament. works ok provide total points acquired every team before every match, want same limited last 3 matches.

i assumed that, sum of points in last 3 matches, including points earned during game in question well. example, if game number 4, want sum points games 4, 3, 2, , 1. if isn't case, change game - 3 game - 2.

# create data  library(dplyr) data.frame(teams = rep(c("team1", "team2", "team3"), 33),            match_number = sample(1:1000, 99, replace = false),            points = sample(1:100, 99, replace = true)) -> dat  # relative match numbers each team dat %>%     group_by(teams) %>%     mutate(game_num = rank(match_number)) %>%     as.data.frame -> z  # sum points in last 3 games  last3 <- function(x) {     z[x, "teams"] -> team     z[x, "game_num"] -> game     game - 3 -> last_three     if(last_three < 1) last_three <- 1     z[z$game_num %in% last_three:game &           z$teams == team, "points"] -> pnts     sum(pnts)  }  sapply(1:nrow(z), fun = last3) -> z$points_last3 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -