Advertisement
Guest User

Untitled

a guest
Mar 18th, 2017
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.11 KB | None | 0 0
  1. library(data.table)
  2. library(stringr)
  3. library(pipeR)
  4.  
  5. # Three rows as a group
  6. nrowGrp <- 3
  7.  
  8. res <- data.table(matrix(c("S11","R1","O11",
  9.                             "S11","R2","O12",
  10.                             "O11","R3","O12",
  11.                             "S21","R1","O21",
  12.                             "S21","R2","O22",
  13.                             "O21","R3","O22",
  14.                             "S11","R1","O11",
  15.                             "S11","R2","O12",
  16.                             "O11","R3","O12"),
  17.                           ncol = 3, byrow = T)) %>>%
  18.     # use pipeR to storage number of columns
  19.     (~ nCols = ncol(.)) %>%
  20.     # add group column
  21.     .[, group_num := ceiling(.I/nrowGrp)] %>%
  22.     # by each group join elements to one string
  23.     .[, .(grp_val = t(.SD) %>% paste0(collapse = ",")), by = .(group_num)] %>%
  24.     # summarise each group count
  25.     .[, .(group_count = .N), by = .(grp_val)] %>%
  26.     # separate string to multiple columns
  27.     .[, paste0("X_", 1:(nCols*nrowGrp)) := data.table(str_split_fixed(grp_val, ",", nCols*nrowGrp))] %>%
  28.     # remove grp_val column
  29.     .[, grp_val := NULL]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement