The following code computes three different features over the same dataset. I'm not sure if the filter_by_day_segment
function can be made tidy or there's a more efficient/short but still readable way of refactor my code.
library(dplyr)
filter_by_day_segment <- function(data, day_segment){
if(day_segment == "daily"){
return(data %>% group_by(local_date))
} else {
return(data %>% filter(day_segment == local_day_segment) %>% group_by(local_date))
}
}
compute_metric <- function(data, metric, day_segment){
if(metric == "countscans"){
data <- filter_by_day_segment(data, day_segment)
return(data %>% summarise(!!paste("sensor", day_segment, metric, sep = "_") := n()))
}else if(metric == "uniquedevices"){
data <- filter_by_day_segment(data, day_segment)
return(data %>% summarise(!!paste("sensor", day_segment, metric, sep = "_") := n_distinct(value)))
}
else if(metric == "countscansmostuniquedevice"){
data <- data %>% group_by(value) %>%
mutate(N=n()) %>%
ungroup() %>%
filter(N == max(N))
data <- filter_by_day_segment(data, day_segment)
return(data %>% summarise(!!paste("sensor", day_segment, metric, sep = "_") := n()))
}
}
data <- read.csv("test.csv")
day_segment <- "daily"
metrics <- c("countscans", "uniquedevices", "countscansmostuniquedevice")
features = data.frame()
for(metric in metrics){
feature <- compute_metric(data, metric, day_segment)
if(nrow(features) == 0){
features <- feature
} else{
features <- merge(features, feature, by="local_date", all = TRUE)
}
}
print(features)
A test CSV file
"local_date","value"
"2018-05-21","FC:44"
"2018-05-21","FC:58"
"2018-05-21","FF:7E"
"2018-05-21","F8:77"
"2018-05-21","F8:77"
"2018-05-22","FB:F1"
"2018-05-22","FC:62"
"2018-05-22","FE:D4"
"2018-05-22","FE:D4"
"2018-05-22","FC:F1"
"2018-05-23","F8:77"
"2018-05-23","F8:77"
"2018-05-23","FF:13"
"2018-05-23","F8:3F"
"2018-05-23","F8:3F"
"2018-05-23","F8:3F"
"2018-05-23","FC:B6"
"2018-05-24","FC:0D"
"2018-05-24","F8:3F"
"2018-05-24","F7:B6"
"2018-05-24","F6:96"
"2018-05-24","F6:96"
"2018-05-24","F6:96"
"2018-05-24","F6:96"
"2018-05-24","F6:96"
"2018-05-24","F6:96"
"2018-05-24","F6:96"
"2018-05-25","FC:A8"
"2018-05-25","FC:44"
"2018-05-25","FC:44"
"2018-05-25","FC:44"
"2018-05-25","FC:44"
"2018-05-25","FC:44"
"2018-05-25","FC:44"
"2018-05-25","FC:44"
"2018-05-25","FC:44"
"2018-05-26","FC:F1"
"2018-05-26","FC:A8"
"2018-05-26","FF:89"
"2018-05-26","FF:89"
"2018-05-26","FF:89"