Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" )) 
like image 432
adl Avatar asked May 04 '18 12:05

adl


People also ask

How do I convert a list to a character vector in R?

To convert a list to a vector in R use unlist() function. This function takes a list as one of the arguments and returns a Vector.

How do I convert a column to a character vector in R?

If we want to turn a dataframe row into a character vector then we can use as. character() method In R, we can construct a character vector by enclosing the vector values in double quotation marks, but if we want to create a character vector from data frame row values, we can use the as character function.

How do I convert a list to characters in R?

Using toString() to Convert List to String. The toString() function can be used to convert elements from list to character string, but this function by default adds a comma separator between the elements.

Can you have a vector of lists in R?

Almost all data in R is stored in a vector, or even a vector of vectors. A list is a recursive vector: a vector that can contain another vector or list in each of its elements. Lists are one of the most flexible data structures in R.


1 Answers

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
like image 63
talat Avatar answered Nov 09 '22 00:11

talat