I have a data frame of dates and times. I've included the pw_backup column as an example of 13 other columns that I have. I found the differences in time between the two columns to create two more columns in the same data frame called dur_days and dur_hour.
first_pmt_date pw_backup
<dttm> <dttm>
1 2016-04-12 18:57:00 2016-04-12 18:44:00
2 2016-05-02 17:06:00 2016-05-02 16:41:00
3 2016-04-06 08:35:00 2016-04-06 08:33:00
4 2016-03-15 22:38:00 2016-03-15 22:12:00
5 2016-04-15 14:36:00 2016-04-15 14:30:00
6 2016-03-22 16:51:00 2016-03-22 16:43:00
7 2016-03-25 07:52:00 2016-05-31 07:40:00
8 2016-04-11 12:39:00 2016-04-11 12:22:00
9 2016-03-08 13:13:00 2016-03-08 09:50:00
10 2016-02-28 13:43:00 2016-05-08 15:44:00
My code gives me the output that I want. I am having trouble changing it into a function, and eventually a for loop looping through all of the columns, so I can add any column to (x) and get the same output.
My Current Code:
paywall_full %>%
filter(paid == 1 & !is.na(pw_backup)) %>%
mutate(dur_days = round(difftime(first_pmt_date, pw_backup, units= 'days')), 0,
dur_hour = difftime(first_pmt_date, pw_backup)) %>%
select(first_pmt_date, pw_backup, dur_days, dur_hour) %>%
summarise(same_day_conv = sum(dur_days == 0)/count_it$pw_backup,
same_hour_conv = sum(dur_hour <= 60 & dur_hour >=
0)/count_it$pw_backup)
The code that I imagined would work, replacing the current column with x so as to add any other column into my function and have the same output.
conv_rate <- function(x)
paywall_full %>%
filter(paid == 1 & !is.na(x)) %>%
mutate(dur_days = round(difftime(first_pmt_date, x, units = 'days')), 0,
dur_hour = difftime(first_pmt_date, x)) %>%
select(first_pmt_date, x, dur_days, dur_hour) %>%
summarise(same_day_conv = sum(dur_days == 0)/count_it$pw_backup,
same_hour_conv = sum(dur_hour <= 60 & dur_hour >=
0)/count_it$pw_backup)
I understand why it doesn't work, if I define a variable beforehand
x <- paywall_full$pw_backup
This overwrites the pipeline every time it passes to another function. I hope my question is clear.
BONUS: Turning this into a loop through my columns and assigning to a data frame.
Thanks in advance!