Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- library(data.table)
- library(stringr)
- library(pipeR)
- # Three rows as a group
- nrowGrp <- 3
- res <- data.table(matrix(c("S11","R1","O11",
- "S11","R2","O12",
- "O11","R3","O12",
- "S21","R1","O21",
- "S21","R2","O22",
- "O21","R3","O22",
- "S11","R1","O11",
- "S11","R2","O12",
- "O11","R3","O12"),
- ncol = 3, byrow = T)) %>>%
- # use pipeR to storage number of columns
- (~ nCols = ncol(.)) %>%
- # add group column
- .[, group_num := ceiling(.I/nrowGrp)] %>%
- # by each group join elements to one string
- .[, .(grp_val = t(.SD) %>% paste0(collapse = ",")), by = .(group_num)] %>%
- # summarise each group count
- .[, .(group_count = .N), by = .(grp_val)] %>%
- # separate string to multiple columns
- .[, paste0("X_", 1:(nCols*nrowGrp)) := data.table(str_split_fixed(grp_val, ",", nCols*nrowGrp))] %>%
- # remove grp_val column
- .[, grp_val := NULL]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement