How to group values of a dataframe by a specific column?

Viewed 48

I'm struggling a little bit when trying to kind of sort a dataframe in R. I'll show you a brief example to explain my problem. Let's suppose I have the following dataframe with two columns:

A----X

A----Y

B----M

C----N

B----P

I'd like the output to be like this

A------X,Y

B------M,P

C------N

Any ideas of how to achieve this?

1 Answers

This is one option:

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
dat <- data.frame(
  var1 = c("A", "A", "B", "C", "B"), 
  var2 = c("X", "Y", "M", "N", "P")
)
  

out <- dat %>% 
  group_by(var1) %>%
  summarise(var2 = list(var2))

out
#> # A tibble: 3 × 2
#>   var1  var2     
#>   <chr> <list>   
#> 1 A     <chr [2]>
#> 2 B     <chr [2]>
#> 3 C     <chr [1]>

out$var2
#> [[1]]
#> [1] "X" "Y"
#> 
#> [[2]]
#> [1] "M" "P"
#> 
#> [[3]]
#> [1] "N"

The list columns above treat each cell as a list with potentially multiple values. If you wanted to be able to use these in future analyses, this way is probably best. However, if you just wanted to see the values, you could paste them together and stick them in a variable as follows:

out2 <- dat %>% 
  group_by(var1) %>%
  summarise(var2 = paste(var2, collapse=","))

out2
#> # A tibble: 3 × 2
#>   var1  var2 
#>   <chr> <chr>
#> 1 A     X,Y  
#> 2 B     M,P  
#> 3 C     N

Created on 2022-04-25 by the reprex package (v2.0.1)

Related