I have data table whose look like this
CodePudding user response:
I would use:
library(dplyr)
data %>%
group_by(SubjectID) %>%
summarise_at(vars(everything()), ~paste0(unique(.), collapse = ",")) %>%
mutate_if(is.character, ~paste0("[", ., "]"))
Output is:
# A tibble: 1 × 4
SubjectID PunchLocation NumOfPunch PunchType
<dbl> <chr> <chr> <chr>
1 102 [1,2,3,4,5] [1,2] [5,6,9]
I used this data:
data <- tibble(
SubjectID = rep(102, 12),
PunchLocation = c(1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 4, 4),
NumOfPunch = c(rep(1, 10), 2, 2),
PunchType = c(5, 6, 5, 6, 9, 5, 6, 5, 6, 9, 5, 6)
)
CodePudding user response:
Using data.table
(with example from @Stephan).
library(data.table)
setDT(data)
fun.collapse <- function(x) sprintf('[%s]', paste(unique(x), collapse=','))
dcast(data, SubjectID ~ .,
value.var = c('PunchLocation', 'NumOfPunch', 'PunchType'),
fun.aggregate = fun.collapse)
## SubjectID PunchLocation NumOfPunch PunchType
## 1: 102 [1,2,3,4,5] [1,2] [5,6,9]