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" ))
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With