简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM