-3

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?

Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
gizgok
  • 7,303
  • 21
  • 79
  • 124
  • 1
    Please show a small reproducible example. Is it a `data.table` object?. – akrun Oct 09 '15 at 05:17
  • It is a matrix object, I update my question – gizgok Oct 09 '15 at 05:26
  • 1
    Also, please do show the expected output and a small input dataset. It will make it easier to test – akrun Oct 09 '15 at 05:27
  • 1
    Unless you will show your data set and your *exact* desired output, we can't really help you. I'm voting to close this as "unclear". One would think that 6 years on this site could teach a person how to post a proper question- guess not. Regardless, you call the object a *datatable* but in comments you call it a *matrix* – David Arenburg Oct 09 '15 at 07:46
  • Please learn how to give a [minimal reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610). – Jaap Oct 09 '15 at 09:58

1 Answers1

-2

Here is an short example using reshaping

library(dplyr)
library(tidyr)

df = data_frame(`1` = c(1, 2), `2` = c(2, 3), `3` = c(3, 4))

df %>%
  gather(variable, value, 2:3) %>%
  mutate(value = value - `1`) %>%
  spread(variable, value)
bramtayl
  • 4,004
  • 2
  • 11
  • 18