markthekoala
markthekoala

Reputation: 1085

Extract a vector from a list

I am trying to cleanly extract a vector from a list.

The code below provides that data that I want. But it returns a list instead of a vector.

lst_demo <- list(a = c("a1", "a2", "a3"), b = c("b1", "b2"), 
                                                    c = "c1")
filter_code <- "b"
result <- lst_demo[names(lst_demo) == filter_code]
# result produces what I expect: "b1" , "b2"
result
# but I want the data type to be a vector rather than a list
class(result)

I understand that I can cast to a vector with as.character but I am looking for a cleaner solution.

Upvotes: 0

Views: 179

Answers (1)

Jonathan Carroll
Jonathan Carroll

Reputation: 3947

Since it's not already added as an answer (but has been said by @thelatemail as a comment)

result <- lst_demo[[filter_code]]
class(result)
[1] "character"

is probably what you're after.

Upvotes: 1

Related Questions