0

I have some data in a dataframe in the following format:

fish flounder
fish mackerel
fish sole
cats tabby
cats black

Columns are columns in a data frame. Note that there are multiple rows for "fish" and "cats". I need a quick way in R to convert to this:

fish flounder,mackerel,sole
cats tabby,black

Again columns are dataframe columns, but the second column must be a comma-separated string without a final comma.

danwiththeplan
  • 153
  • 1
  • 2
  • 11

1 Answers1

0

Libraries

library(dplyr)

Data

df <-
  structure(list(col1 = c(10L, 8L, 5L, 4L, 6L, 3L), col2 = c(11L,9L, 6L, 3L, 4L, 6L), col3 = c(12L, 10L, 7L, 5L, 7L, 7L), group = c("a","a", "b", "b", "c", "c")), class = "data.frame", row.names = c(NA,-6L))                                                                                                          -20L))
        
    V1       V2
1 fish flounder
2 fish mackerel
3 fish     sole
4 cats    tabby
5 cats    black
                                                                                                                    

Code

df %>% 
  group_by(V1) %>% 
  summarise(V2 = paste(V2,collapse = ","))

Result

# A tibble: 2 x 2
  V1    V2                      
  <chr> <chr>                   
1 cats  tabby,black            
2 fish  flounder,mackerel,sole
Vinícius Félix
  • 8,448
  • 6
  • 16
  • 32