I have a data frame that generally looks like
df.data <- data.frame(x=sample(1:9, 10, replace = T), y=sample(1:9, 10, replace=T), vx=sample(-1:1, 10, replace=T), vy=sample(-1:1, 10, replace=T))
x and y are positions. vx and vy are the x, y values ββfor the 2d vector. I want to take this data frame and "bin" based on the values ββof x and y, but do the calculations on vx and vy. This function does this, except that it uses a loop that will be too slow for my dataset.
slowWay <- function(df) { df.bin <- data.frame(expand.grid(x=0:3, y=0:3, vx=0, vy=0, count=0)) for(i in 1:nrow(df)) { x.bin <- floor(df[i, ]$x / 3) y.bin <- floor(df[i, ]$y / 3) print(c(x.bin, y.bin)) df.bin[df.bin$x == x.bin & df.bin$y == y.bin, ]$vx = df.bin[df.bin$x == x.bin & df.bin$y == y.bin, ]$vx + df[i, ]$vx df.bin[df.bin$x == x.bin & df.bin$y == y.bin, ]$vy = df.bin[df.bin$x == x.bin & df.bin$y == y.bin, ]$vy + df[i, ]$vy df.bin[df.bin$x == x.bin & df.bin$y == y.bin, ]$count = df.bin[df.bin$x == x.bin & df.bin$y == y.bin, ]$count + 1 } return(df.bin) }
Is this type of 2D binning impossible?