R converting a single week row, to 7 day rows -
i've seen few similar examples , threads online morning, nothing find quite particular case. have dataframe looks this:
week income views partner 09/07/15 2000 345 bob 09/07/15 460 11980 jane 08/31/15 304 678 mark
what need each "week row" replicated each day within week. don't need worry how alter other variables divided 7, can perform operations without assistance. having trouble expanding week row 7 rows total describe each day within week, so:
week income views partner 09/07/15 2000 345 bob 09/08/15 2000 345 bob 09/09/15 2000 345 bob 09/10/15 2000 345 bob 09/11/15 2000 345 bob 09/12/15 2000 345 bob 09/13/15 2000 345 bob 09/07/15 460 11980 jane 09/08/15 460 11980 jane 09/09/15 460 11980 jane 09/10/15 460 11980 jane 09/11/15 460 11980 jane 09/12/15 460 11980 jane 09/13/15 460 11980 jane 08/31/15 304 678 mark 09/01/15 304 678 mark 09/02/15 304 678 mark 09/03/15 304 678 mark 09/04/15 304 678 mark 09/05/15 304 678 mark 09/06/15 304 678 mark
like said other data points can left @ na (i can na.locf easily) or have them copied down columns.
thanks in advance!
the code below uses mapply
create new rows each combination of week
, partner
. then, wrap in do.call(rbind, ...)
put each subgroup single data frame. i've left original week
column in final output illustation, can removed.
# sample data dat = read.table(text=" week income views partner 09/07/2015 2000 345 bob 09/07/2015 460 11980 jane 08/31/2015 304 678 mark" , header=true, stringsasfactors=false) dat$week = as.date(dat$week, "%m/%d/%y") newdat = do.call(rbind, mapply(function(w,p) { data.frame(day=seq(w, w+6, 1), dat[dat$week==w & dat$partner==p, ]) }, dat$week, dat$partner, simplify=false)) newdat day week income views partner 1 2015-09-07 2015-09-07 2000 345 bob 2 2015-09-08 2015-09-07 2000 345 bob 3 2015-09-09 2015-09-07 2000 345 bob 4 2015-09-10 2015-09-07 2000 345 bob 5 2015-09-11 2015-09-07 2000 345 bob 6 2015-09-12 2015-09-07 2000 345 bob 7 2015-09-13 2015-09-07 2000 345 bob 8 2015-09-07 2015-09-07 460 11980 jane 9 2015-09-08 2015-09-07 460 11980 jane 10 2015-09-09 2015-09-07 460 11980 jane 11 2015-09-10 2015-09-07 460 11980 jane 12 2015-09-11 2015-09-07 460 11980 jane 13 2015-09-12 2015-09-07 460 11980 jane 14 2015-09-13 2015-09-07 460 11980 jane 15 2015-08-31 2015-08-31 304 678 mark 16 2015-09-01 2015-08-31 304 678 mark 17 2015-09-02 2015-08-31 304 678 mark 18 2015-09-03 2015-08-31 304 678 mark 19 2015-09-04 2015-08-31 304 678 mark 20 2015-09-05 2015-08-31 304 678 mark 21 2015-09-06 2015-08-31 304 678 mark
Comments
Post a Comment