1

I am trying to convert a table of inputs and outputs currently listed as columns in a data.table (think like an middle/highschool algebra textbook introducing functions, see example below) into a matrix with the inputs as row and column labels and the outputs as matrix entries.

> dt <- data.table(x = c("a","b","c"), y = c("T1", "T2", "T2"), z = c(10:12))
> dt
   x  y  z
1: a T1 10
2: b T2 11
3: c T2 12
> dt2 <- data.table(x = c("a","b","c"), T1 = c(10,0,0), T2 = c(0,11,12))
> dt2
   x T1 T2
1: a 10  0
2: b  0 11
3: c  0 12

My first thought in generating dt2 was to create it but filled with 0's, then create a function f(x,y) to take the "z" associated with each (x,y) in dt to its corresponding position, (x,y), in dt2, that is:

> dt2attempt <- data.table(x = c("a","b","c"), T1 = c(0,0,0), T2 = c(0,0,0))
> dt2attempt
   x T1 T2
1: a  0  0
2: b  0  0
3: c  0  0

I am stuck on creating the function f(x,y) to associate dt to dt2attempt, thus generating dt2. Is there a better approach? Any advice or functions provided will be greatly appreciated.

1 Answers1

1

dt2 can be generated with dcast:

> dcast(dt, x ~ y, value.var = 'z', fill = 0)
   x T1 T2
1: a 10  0
2: b  0 11
3: c  0 12
mt1022
  • 16,834
  • 5
  • 48
  • 71