r - Replacing the first date instance if a condition is satisfied -


i have snapshot data in dataframe this:

zz <- "id  created  snap    stage alpha   2012-09-07  2014-01-02  alpha   2012-09-07  2014-10-01  end beta    2012-08-26  2014-01-04  b beta    2012-08-26  2014-06-19  c beta    2012-08-26  2014-11-21  end gamma   2014-01-04  2014-01-04  gamma   2014-01-04  2014-03-07  b gamma   2014-01-04  2014-03-28  c gamma   2014-01-04  2014-03-29  end delta   2014-07-14  2014-07-15  delta   2014-07-14  2014-09-26  c delta   2014-07-14  2015-02-06  end" df <- read.table(text=zz, header = t) 

i need replace snap date created date whenever created date before 2014-01-01. want replace snap date first instance of observation. although ids move through a-b-c-end in order, id doesn't have start @ a.

for example, i'm looking @ output:

id  created snap    stage alpha   2012-09-07  2012-09-07  alpha   2012-09-07  2014-10-01  end beta    2012-08-26  2012-08-26  b beta    2012-08-26  2014-06-19  c beta    2012-08-26  2014-11-21  end gamma   2014-01-04  2014-01-04  gamma   2014-01-04  2014-03-07  b gamma   2014-01-04  2014-03-28  c gamma   2014-01-04  2014-03-29  end delta   2014-07-14  2014-07-15  delta   2014-07-14  2014-09-26  c delta   2014-07-14  2015-02-06  end 

notice gamma , delta remain same, alpha in stage a has snap date replaced, beta in stage b.

here's dplyr approach - start "mutate_each" make sure both "created" , "snap" formatted proper dates. group data "id" , use "mutate" "replace" make required changes "snap" column (we check created before cutoff date , row_number 1, i.e. first row in id group):

library(dplyr) df %>%    mutate_each(funs(as.date(.)), created, snap) %>%   group_by(id) %>%   mutate(snap = replace(snap, which(created < as.date("2014-01-01") & row_number() == 1), created))  #source: local data frame [12 x 4] #groups: id # #      id    created       snap stage #1  alpha 2012-09-07 2012-09-07     #2  alpha 2012-09-07 2014-10-01   end #3   beta 2012-08-26 2012-08-26     b #4   beta 2012-08-26 2014-06-19     c #5   beta 2012-08-26 2014-11-21   end #6  gamma 2014-01-04 2014-01-04     #7  gamma 2014-01-04 2014-03-07     b #8  gamma 2014-01-04 2014-03-28     c #9  gamma 2014-01-04 2014-03-29   end #10 delta 2014-07-14 2014-07-15     #11 delta 2014-07-14 2014-09-26     c #12 delta 2014-07-14 2015-02-06   end 

Comments

Popular posts from this blog

java - Could not locate OpenAL library -

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

sorting - opencl Bitonic sort with 64 bits keys -