r - How can I use multiple conditionals and match to create a new variable? -


i have following data

name <- c("kobe bryant", "kobe bryant", "kobe bryant",            "kobe bryant", "kobe bryant", "kobe bryant",            "lebron james", "lebron james", "lebron james",            "lebron james", "kevin durant", "kevin durant",           "kevin durant", "kevin durant", "kevin durant")  date <- as.date(c("2015-05-14", "2015-05-15", "2015-05-19", "2015-05-21",             "2015-05-24", "2015-05-28", "2015-05-14", "2015-05-20",             "2015-05-21", "2015-05-23", "2015-05-22", "2015-05-24",             "2015-05-28", "2015-06-02", ""2015-06-04"))  df <- data.frame c(name, date)  desired_output <- c(1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0)  df2 <- data.frame c(name, date, desired_output) 

i want create new column identifies back-to-back games (playing game 2 consecutive days) specific player.

output of column: 1 (if b2b) 0 if not.

both first day , second day of b2b should have 1.

this split-apply-combine problem (since need handle each player separately), can in base r (by(), aggregate(), ...) or variety of packages (plyr, dplyr, data.table) ... here's plyr() solution.

name <- rep(c("kobe bryant", "lebron james", "kevin durant"),             c(6,4,5)) date <- as.date(c("2015-05-14", "2015-05-15", "2015-05-19",   "2015-05-21","2015-05-12", "2015-05-28", "2015-05-14",   "2015-05-16","2015-05-17", "2015-05-21", "2015-05-22",   "2015-05-24","2015-05-28","2015-06-02","2015-06-10")) dd <- data.frame(name,date) b2b <- function(x,ind=false) {     x0 <- head(x,-1)  ## last     x1 <- tail(x,-1)  ## first     comp <- abs(head(x,-1)-tail(x,-1))==1     res <- c(comp,false) | c(false,comp)     if (ind) {         w <- res==1 & c(0,res[-length(res)])==1         res[w] <- 2     }     return(res) } library("plyr") ddply(dd,"name",       transform,          b2b=as.numeric(b2b(date)),          b2b_ind=as.numeric(b2b(date,ind=true))) 

my code has automatically reorganized players alphabetical order (because players got turned factor levels in alphabetical order, , ddply returns data in rearranged order). if that's important can make sure factors ordered way want before beginning.


Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -