I have a df with two variables, names and dates. I would like to create a new column (new_dates) which takes the first date belonging to each person (each person should have just one repeated date in this column) and add 30 days to each date as the rows descend.
Desired output is below. So row1 for each person holds the original date, row2 holds row1+30, row3 holds row2+30 and so on.
dff
names dates new_dates
1 john 2010-06-01 2010-06-01
2 john 2010-06-01 2010-07-01
3 john 2010-06-01 2010-07-31
4 john 2010-06-01 2010-08-30
5 mary 2010-07-09 2010-07-09
6 mary 2010-07-09 2010-08-08
7 mary 2010-07-09 2010-09-07
8 mary 2010-07-09 2010-10-07
9 tom 2010-06-01 2010-06-01
10 tom 2010-06-01 2010-07-01
11 tom 2010-06-01 2010-07-31
12 tom 2010-06-01 2010-08-30
I thought I could use transform for this. Here is my attempt at it - but it doesn't quite work for me.
dt <- transform(df, new_date = c(dates[2]+30, NA))
sorry, quickly read the question and didn't realize what you were doing at first.
definitely a brute-force method, and my programming is not, how you say, elegant, but it seems to give the desired result:
What you're exactly looking for is a bit confusing to me. I'm assuming that you're starting with a small data frame that looks like this:
And then want to add N rows to your data frame that have your new dates column. If so, I'm sure there are some pre-packaged ways to do this but you could also use two nested
lapply()
calls. The inner most call would simply add a new column where newdates is set to be some multiple of 30 plus your original date and then the outer most call would be passing in your multiple of 30. For example:Anyway, this method isn't ideal and may be confusing so let me know if this is what you're looking for and I can provide more details about what is going on.
data.table
makes this easy. Once you convert to a data table, it's basically one command. The main problem you're having with your version is that you need to split the data by name first, so you can get the minimum date for each person, and then add the appropriate mutiple of 30 days to each date.EDIT: here is a version that hopefully shows why yours didn't work. I still prefer
data.table
, but hopefully since this is basically very close to what you were doing it makes it clear what you need to change:Starting with the bottom line (
do.call...
), thesplit
call makes a list with three data frames, one with the values for John, one for those for Mary, and one for those for Tom. Thelapply
then runs each of those data frames through there_date
function, which adds thenew_dates
column, and finally, thedo.call
/rbind
stitches it back together into one data frame.