How to return cells based on identifier in R

3

I need to return the class of a specific id for a table. Often a single id encodes several classes:

id<-c("A","B","C","D","C","B","A")
clas<-c(1,2,2,2,3,3,4)
tab<-data.frame(id,clas)

What I need is to make a data.frame that returns as follows:

   id clas
1  1    A
2  2  BCD
3  3   CB
4  4    A

Someone can help me

    
asked by anonymous 28.03.2017 / 21:38

1 answer

4

A relatively simple way to do this is to use dplyr :

tab <- tab %>%
  group_by(id) %>%
  summarise(clas = paste0(clas, collapse = ""))

Result:

> tab
# A tibble: 4 × 2
     id  clas
  <dbl> <chr>
1     1     A
2     2   BCD
3     3    CB
4     4     A
    
28.03.2017 / 21:48