I have two tables with the same columns. I want to merge them together summing the metrics in rows if the dimensions are the same.
Here is a lengthy code that does exactly what I need:
if ("dimension14" %in% colnames(data)) {
if ("segment" %in% colnames(data)) {
data <- aggregate(. ~ date + dimension14 + segment, data, sum)
} else {
data <- aggregate(. ~ date + dimension14, data, sum)
}
} else if ("dimension55" %in% colnames(data)) {
if ("channelGrouping" %in% colnames(data)) {
data <- aggregate(. ~ date + dimension55 + channelGrouping, data, sum)
} else {
data <- aggregate(. ~ date + dimension55, data, sum)
}
} else if ("channelGrouping" %in% colnames(data)) {
data <- aggregate(. ~ date + channelGrouping, data, sum)
} else {
data <- aggregate(. ~ date, data, sum)
}
# ... other similar lines of code here
data <- data[order(data$date), ]
I want to simplify that so it uses a dynamic list of dimensions but the aggregating line of code doesn’t work:
columns = c("date")
if ("dimension14" %in% colnames(data)) columns <- c(columns, "dimension14")
if ("dimension55" %in% colnames(data)) columns <- c(columns, "dimension55")
if ("channelGrouping" %in% colnames(data)) columns <- c(columns, "channelGrouping")
if ("segment" %in% colnames(data)) columns <- c(columns, "segment")
data <- aggregate(. ~ .[columns], data, sum) ### <== This doesn't work
data <- data[order(data$date), ]