smallboy
smallboy

Reputation: 43

Convert lists inside a list to a character vector

I need b to be a list but elements in b should be a character vector

a <- list('foo bar','foobar')
b <- a %>% stringr::str_to_lower() %>% strsplit("[[:space:]]")

Here b is a list of words for every element in a. But b[1] is also a list. I need b[1] to be a character vector

Tried unlist(b, recursive = FALSE) . But it is converting b to a vector. I just need b to be a flat list with two character vectors 1) "foo" "bar" 2) "foobar"

Upvotes: 0

Views: 108

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226047

b[1] is a list because using [i] to extract things from a list always returns a list; if i is a vector of length 1 then you get a list of length 1. b[[1]] returns a character vector as requested.

> b[[1]]
[1] "foo" "bar"
> str(b[[1]])
 chr [1:2] "foo" "bar"

As Hadley Wickham posted on twitter:

enter image description here

Upvotes: 1

Related Questions