I have a data set in chronological order which I have imported to R using:
mydata <- read.csv(file="test.csv",stringsAsFactors=FALSE)
winner loser winner_matches loser_matches
tom andy 1 1
andy greg 2 1
greg tom 2 2
ave(mydata$winner_name==mydata$winner_name, mydata$winner_name, FUN=cumsum)
You're really close to getting
ave to work. The
cumsum function doesn't know how to handle text so I created a dummy column that's equal to 1 for each row. That gives
cumsum something to count.
Here's a sample dataframe.
mydata <- data.frame( winner = c("tom", "andy", "greg", "tom", "gary"), loser = c("andy", "greg", "tom", "gary", "tom"), stringsAsFactors = FALSE )
And here's the code to add the two new columns.
library(tidyverse) mydata <- mutate(mydata, one = 1) # Add dummy column # Use ave() to calculate both the wins and losses mydata$winner_matches <- ave(x = mydata$one, mydata$winner, FUN = cumsum) mydata$loser_matches <- ave(x = mydata$one, mydata$loser, FUN = cumsum) mydata <- select(mydata, -one) # Remove dummy column