-1

I'm running into an RStudio data issue regarding properly melting data. It currently is in the following form:

Campaign, ID, Start Date, End Date, Total Number of Days, Total Spend, Total Impressions, Total Conversions

I would like my data to look like the following:

Campaign, ID, Date, Spend, Impressions, Conversions

Each 'date' should contain a specific day the campaign was run while spend, impressions, and conversions should equal Total Spend / Total # of Days, Total Impressions / Total # of Days, and Total Conversions / Total # of Days, respectively.

I'm working in RStudio so a solution in R is needed. Does anyone have experience manipulating data like this?

Marc
  • 9
  • 1
  • 1
    Welcome to SO. Please, [edit] your question and provide a [mcve] plus the expected result. In particular, it is unclear what you mean by *Total Spend / Total # of Days* when you refer to a specific data. Do you mean *Spend to date* or *Total Spend in overall period (start date to end date)*? – Uwe Feb 04 '19 at 00:04

1 Answers1

0

This works, but it's not particularly efficient. If your data is millions of rows or more, I've had better luck using SQL and inequality joins.

library(tidyverse)

#create some bogus data
data <- data.frame(ID = 1:10,
                   StartDate = sample(seq.Date(as.Date("2018-01-01"), as.Date("2018-12-31"), "day"), 10),
                   Total = runif(10)) %>% 
  mutate(EndDate = StartDate + floor(runif(10) * 14))


#generate all dates between the min and max in the dataset
AllDates = data.frame(Date = seq.Date(min(data$StartDate), max(data$EndDate), "day"),
                      Dummy = TRUE)

#join via a dummy variable to add rows for all dates to every ID
data %>% 
  mutate(Dummy = TRUE) %>% 
  inner_join(AllDates, by = c("Dummy" = "Dummy")) %>% 
  #filter to just the dates between the start and end
  filter(Date >= StartDate, Date <= EndDate) %>% 
  #divide the total by the number of days
  group_by(ID) %>% 
  mutate(TotalPerDay = Total / n()) %>% 
  select(ID, Date, TotalPerDay)

# A tibble: 91 x 3
# Groups:   ID [10]
        ID    Date       TotalPerDay
      <int>   <date>      <dbl>
  1     1 2018-06-21     0.00863
  2     1 2018-06-22     0.00863
  3     1 2018-06-23     0.00863
  4     1 2018-06-24     0.00863
  5     1 2018-06-25     0.00863
  6     1 2018-06-26     0.00863
  7     1 2018-06-27     0.00863
  8     1 2018-06-28     0.00863
  9     1 2018-06-29     0.00863
  10     1 2018-06-30     0.00863
  # ... with 81 more rows
Jordo82
  • 796
  • 4
  • 14