I have a datatable dt in which what I want to do column subtraction. I want to output a new datatable dt_op where,
dt <- acast(raw, a~b, value.var="z")
dt_op[1, 1] <- dt[1, 2] - dt[1, 1]
dt_op[1, 2] <- dt[1, 3] - dt[1, 1]
dt_op[1, 3] <- dt[1, 4] - dt[1, 1]
dt_op[1, 4] <- dt[1, 5] - dt[1, 1]
dt_op[1, 5] <- dt[1, 7] - dt[1, 6]
dt_op[1, 6] <- dt[1, 8] - dt[1, 7]
I want to subtract 2,3,4,5 column from 1 and then columns 7,8,9, 10 from 6 so on so forth.
I have done a attempt using loops but that is slow and inappropriate.
temp <- function(r) {
i = 1
l = length(r)
op <- list()
for(j in 2:l) {
op[[j-1]] <- r[j] - r[i]
if (j -i == 4) {
j = j + 2
i = i + 5
}
}
return(op)
}
I call this with apply on the datatable. How to do it the right way?