1

I would like to transform following data table

da<-data.table(Gr=c("A","B","B","B","A","B"),
   mmoSze=c("SCRSCR","SCRSCR","OSNOSN","Eig.SCRSCR","Eig.SCRSCR","Eig.OSNOSN"),
              SCR=c(25, 43, 61, 79, 97, 115))

into:

da.goal<-data.table(GR=c(   "A",    "B"),
SCRSCR=c(   25, 43),
OSNOSN=c(   0,  61),
Eig.SCRSCR=c(   97, 79),
Eig.OSNOSN=c(   0,  115))

using data.table! One possible undesirable way would be to divide the table and then merge them. What is the elegant way to do it?

maniA
  • 1,437
  • 2
  • 21
  • 42
  • you have the `melt` function to transform from wide to long format, and `dcast` to transform from long to wide. See https://cran.r-project.org/web/packages/data.table/vignettes/datatable-reshape.html – denis Jul 05 '19 at 21:11

2 Answers2

2

dcast() is a data.table function, and I think this is elegant enough:

dcast(da, Gr ~ mmoSze)

Only problem is that you get NA instead of 0, but then you can do:

res = dcast(da, Gr ~ mmoSze)
res[is.na(res)] <- 0
Fino
  • 1,774
  • 11
  • 21
1

You need to convert your long table to wide:

dcast(da, Gr ~ mmoSze, fill = 0)

fill = 0 will put a zero where it can't find a value.

PavoDive
  • 6,322
  • 2
  • 29
  • 55