How to return cells based on identifier in R

Asked

Viewed 51 times

3

need to return the class of a specific id to 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 to do is make a data.frame that returns as follows:

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

Can someone help me

1 answer

4

A relatively simple way to do this is by using the dplyr:

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

Upshot:

> tab
# A tibble: 4 × 2
     id  clas
  <dbl> <chr>
1     1     A
2     2   BCD
3     3    CB
4     4     A
  • His idea was great and very simple, a tiny correction in the script is to exchange id with Clas: tab_resutlado <- tab %>% group_by(Clas) %>% summarise(id = paste0(id, Collapse = ""))

  • Is it OK to do this with a 1 million line table? it summarizes the classes in 6 lines and does not return the table

  • Shouldn’t... Are you sure you want to do the group by Clas? I think in your example it’s reversed!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.