-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMarkov attribution.R
196 lines (159 loc) · 4.88 KB
/
Markov attribution.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# Minimum config
# Set BigQuery data set ID, e.g. "scitylana-1048:scitylana"
datasetId <- ""
# Set Google Analytics view ID, e.g. "14409649"
viewId <- ""
####################################################################################
# Additional config
# Looback steps in the user journey. Integer between 1 and infinte
journeyLookback = 5
####################################################################################
install_load <- function (package1, ...) {
packages <- c(package1, ...)
for (package in packages) {
if (package %in% rownames(installed.packages()))
do.call(library, list(package))
else {
install.packages(
package,
repos = c(
"https://cloud.r-project.org",
"http://owi.usgs.gov/R/"
),
dependencies = NA,
type = getOption("pkgType")
)
do.call(library, list(package))
}
}
}
# Auto Install/Load package
install_load("bigrquery",
"ChannelAttribution",
"reshape",
"ggplot2",
"stringr",
"scales")
# Load Scitylana data from BigQuery
bqInfo <- strsplit(datasetId, ':')
bqBilling <- bqInfo[[1]][1]
bqTable <- bqInfo[[1]][2]
conversionMetric = "M_transactionRevenue"
sourceDimension = "channel"
conversionMetricColumn = "sum(M_transactionRevenue)"
sourceDimensionColumn = "channelGrouping"
sql <- paste0('
select sl_userId,
sl_sessionId as sessionCount,
',conversionMetricColumn,' as ',conversionMetric,',
',sourceDimensionColumn,' as ',sourceDimension,'
from `', bqTable, ".", viewId, '`
where
sl_sessionId != "(not set)"
and sl_userId in (
select
sl_userId
from
`', bqTable, ".", viewId, '`
where
sl_userId != "(not set)"
group by
sl_userId
having
',conversionMetricColumn,' > 0
)
group by
sl_userId,
sl_sessionId,
',sourceDimensionColumn,'
order by
sl_sessionId,
min(sl_timeStamp) ')
tb <- bq_project_query(bqBilling, sql)
dataset <- bq_table_download(tb)
####################################################################################
#Validate dataset
N = nrow(dataset)
if(N==0) stop('Dataset is empty')
#Order the data by our primary key, user id
dataset <- dataset[order(dataset$sl_userId, dataset$sessionCount), ]
sl_userId = -1
outputRowCount = 1
convPath = ""
lastSource = ""
total_conversions = c()
total_conversion_value = c()
convPaths = data.frame(
path = rep("", N),
total_conversions = rep(NA, N),
total_conversion_value = rep(NA, N),
stringsAsFactors = FALSE
)
converted = FALSE
for (row in 1:N) {
sl_userIdNew = paste0(dataset[row,]["sl_userId"][1, ])
# New user?
if (sl_userIdNew != sl_userId) {
if (row == 1)
sl_userId = sl_userIdNew
converted = FALSE
lastSource = ""
}
# Focus only on 1st conversion - skip the rest
if (converted == FALSE) {
src = dataset[row,][sourceDimension][1, ]
source = gsub(pattern = "\\(not set\\)/",
replacement = "",
x = src)
# Workaround, ChannelAttribution package doesn't tolerate spaces in sources, replace spaces with ^
source = gsub(pattern = " ",
replacement = "^",
x = source)
if (row == 1)
sl_userId = sl_userIdNew
# handle user switch
if (sl_userIdNew != sl_userId) {
sl_userId = sl_userIdNew
convPath = ""
lastSource = ""
}
# Build converted path
if (convPath == "") {
convPath = paste0(source)
} else {
if (source != lastSource) {
convPath = paste(convPath, source, sep = " > ")
}
}
# Found conversion path?
revenue = strtoi(dataset[row,][conversionMetric][1, ], base = 0L)
if (is.na(revenue))
revenue = 0
if (revenue > 0) {
# ignore repeat source
convPaths[outputRowCount,] <- list(convPath, 1, revenue)
outputRowCount = outputRowCount + 1
converted = TRUE
}
lastSource = source
}
}
# Trim exceeding rows
convPaths = head(convPaths, outputRowCount - N)
if(nrow(convPaths) == 1) stop('The users found in this dataset has no conversions')
# Aggregate per path
convPathsAggr <- aggregate(. ~ path, convPaths, sum)
# Generate last, linear and first touch models
H <- heuristic_models(convPathsAggr, 'path', 'total_conversions', var_value='total_conversion_value')
# Train Markov Model
M <- markov_model(convPathsAggr,
'path',
'total_conversions',
var_value = 'total_conversion_value',
order = journeyLookback)
# Merge by channel if we compare
M <- merge(H, M, by='channel_name')
# Rename ^ back to space
M$channel_name <- str_replace_all(M$channel_name, "\\^", " ")
# Write to file
write.csv(M, file = paste0("markov_attribution_", viewId, "_", format(Sys.time(), "%Y%m%d_%H%M%S"), ".csv"))