Please show me the proper 'r' way.
I have 5 locations. Every day each location will have 0 or 2 values. I want to get the possible combinations of locations by day. The code below works but I don't think it's very good. Is there a better way to do this? I've tried lots of different variations of apply, aggregate, melt, cast, etc. But this is all I've gotten to work.
Please note that in my sample data every location has 2 readings every day. But in reality a location will have 0 or 2 readings every day so the combinations each day can differ.
d1 = rep(seq(as.Date("2015-01-01"), as.Date("2015-01-10"), by = "days"), each = 10)
v1 = round(runif(100, -300, 300))
results =
data.frame(
Date = d1,
Location = c(1:5),
Value = v1
)
dates = unique(lapply(results$Date, function(x) as.Date(x)))
process = function(d, c) {
x = results[(results$Date == d & results$Location %in% c), ]
print(x)
}
for (i in 1:length(dates)){
results.sub = results[as.Date(results$Date) == dates[i], ]
loc = unique(results.sub$Location)
for (m in 1:length(loc)){
combos = combn(loc,m)
for (c in 1:ncol(combos)){
process(dates[i],combos[,c])
}
}
}
I've looked at lots of other SO answers but couldn't find one to fit my scenario.
Thank you for your help.
If locations 1, 2, and 3 reported for the day then for that day I need all combinations of:
1
2
3
1 2
1 3
2 3
1 2 3
Found a solution at Combinations by group in R:
library(dplyr)
results %>% group_by(Date) %>% do(data.frame(t(combn(unique(.$Location), 5))))
This isn't a complete solution as it only solves for n items in a combination, not all possibilities of n. But this with the answer below should be very close.
x = c(1,2,3) # your input
as.character(unlist(
lapply(1:length(x), function(m){
y = combn(x,m = m)
return(lapply(as.data.frame(y), paste, collapse = " "))
})
))
# [1] "1" "2" "3" "1 2" "1 3" "2 3" "1 2 3"