adl
adl

Reputation: 1441

r-convert list column into character vector where lists are characters

I'm trying to convert a list into a single character value, or basically go from this:

test <- data.frame(a = c(1,1,1,2,2,2), b = c("a", "b", "c", "d", "e", "f" )) %>% 
  group_by(a) %>% summarise(b = list(b))

to this:

test <- data.frame(a = c(1,2), b = c("a, b, c", "d, e, f" )) 

Upvotes: 9

Views: 10771

Answers (2)

DJack
DJack

Reputation: 4940

As suggested by the OP, I post my comment as an answer for future reference.

Starting from the raw data frame, you can do:

data.frame(a = c(1,1,1,2,2,2), b = c("a", "b", "c", "d", "e", "f")) %>% 
   group_by(a) %>%
   summarise(b = paste(b, collapse = ","))

## A tibble: 2 x 2
#      a b    
#  <dbl> <chr>
#1  1.00 a,b,c
#2  2.00 d,e,f

Upvotes: 3

talat
talat

Reputation: 70336

Here you go:

test %>% 
  mutate(b = sapply(b, toString))

## A tibble: 2 x 2
#      a b      
#  <dbl> <chr>  
#1    1. a, b, c
#2    2. d, e, f

Upvotes: 17

Related Questions