I am trying to update by reference multiple columns of a data.table using the output of a function. As an example I set up a fake function and a fake dt:
exampleDT <- data.table(1:6, 0,0,0,0,0,0,0,0)
exampleDF <- as.data.frame(exampleDT)
exampleFUN <- function(x){seq(x, x+7)}
expected output:
for(i in 1:NROW(exampleDF)){
exampleDF[i, 2:9] <- exampleFUN(i)
}
V1 V2 V3 V4 V5 V6 V7 V8 V9
1 1 1 2 3 4 5 6 7 8
2 2 2 3 4 5 6 7 8 9
3 3 3 4 5 6 7 8 9 10
4 4 4 5 6 7 8 9 10 11
5 5 5 6 7 8 9 10 11 12
6 6 6 7 8 9 10 11 12 13
Note, my DT has million rows, I'd appreciate if you could point out a fast solution.
EDIT1: The function I'm providing is just an example, the true one is more complex. It finds the neighbors cells in a raster, considering the borders. The first column contain the cell ID for which I want the neighbors. Ideally the code would be something like:
for(i in 1:NROW(exampleDT)) {
set(exampleDT, i=i, j=2:9, value=exampleFUN(exampleDT[i, V1]))
}
EDIT2: The actual function I am planning to use:
neighbourF <- function(CellID, cols, ncell) {
if(CellID == 1) { # Top right corner
return(c(NA, NA, NA, CellID + cols , CellID + (cols + 1) , CellID + 1, NA, NA))
} else if(CellID %in% 2:(cols-1)) { # Top row
return(c(NA, CellID - 1 , CellID + (cols - 1) , CellID + cols , CellID + (cols + 1) , CellID + 1, NA, NA))
} else if(CellID == cols) { # Top right corner
return(c(NA, CellID - 1 , CellID + (cols - 1) , CellID + cols, NA, NA, NA, NA))
} else if(CellID %in% seq(cols+1, ncell-cols, cols)) { # Left column
return(c(NA, NA, NA, CellID + cols , CellID + (cols + 1) , CellID + 1 , CellID - (cols - 1) , CellID - cols))
} else if(CellID == ncell-cols+1) { # Bottom left corner
return(c(NA, NA, NA, NA, NA, CellID + 1 , CellID - (cols - 1) , CellID - cols))
} else if(CellID %in% (ncell-cols+2):(ncell-1)) { # Bottom row
return(c(CellID - (cols + 1) , CellID - 1 , NA, NA, NA, CellID + 1 , CellID - (cols - 1) , CellID - cols))
} else if(CellID == ncell) { # Bottom right corner
return(c(CellID - (cols + 1) , CellID - 1 , NA, NA, NA, NA, NA, CellID - cols))
} else if(CellID %in% seq(2*cols, ncell-cols, cols)) { # Right column
return(c(CellID - (cols + 1) , CellID - 1 , CellID + (cols - 1) , CellID + cols , NA, NA, NA, CellID - cols))
} else {
return(c(CellID - (cols + 1) , CellID - 1 , CellID + (cols - 1) , CellID + cols , CellID + (cols + 1) , CellID + 1 , CellID - (cols - 1) , CellID - cols))
}
}
Cheers