0

e.g

ID | Class
1  | A
2  | B 
3  | A
2  | A
4  | B 
1  | C

**Becomes**

Class | ID
A     | c(1, 2, 3)
B     | c(2, 4)
C     | c(1)

I think the code below somewhat achieves this, I can't help but think that there may be a better way to do this. I am not picky about the form of the output, I require the ID's to be in a list or vector of some sort and not as just one big string

uniqueClasses <- unique(data$Class)
lapply(uniqueClasses, function(x) unique(Hier.data %>% filter(Class == x) %>% select(SiteUnit)))
Oamar Kanji
  • 1,824
  • 6
  • 24
  • 39

1 Answers1

1

A possible solution, based on tidyverse:

library(tidyverse)

df <- data.frame(
  stringsAsFactors = FALSE,
  ID = c(1L, 2L, 3L, 2L, 4L, 1L),
  Class = c("A", "B", "A", "A", "B", "C")
)

df %>% 
  group_by(Class) %>% 
  summarise(ID = str_c(ID, collapse = ","))

#> # A tibble: 3 × 2
#>   Class ID   
#>   <chr> <chr>
#> 1 A     1,3,2
#> 2 B     2,4  
#> 3 C     1
PaulS
  • 21,159
  • 2
  • 9
  • 26