I am looking for a function that homogenizes vectors composed with c()
, lists, and values passed as separate arguments. Consider the following three function calls:
to_list( c(1, 2, 3) ) # Case 1
to_list( list(1, 2, 3) ) # Case 2
to_list( 1, 2, 3 ) # Case 3
The desired output for all three is a list:
# List of 3
# $ : num 1
# $ : num 2
# $ : num 3
purrr::splice()
works correctly on Cases 2 and 3. However, for Case 1 it nests the vector inside a list:
# List of 1
# $ : num [1:3] 1 2 3
I end up needing a "hack" that looks for any such nested vectors, converts them to lists and then unnests the resulting list-of-lists:
library( purrr )
to_list <- function(...) {
splice(...) %>% map_if( ~(length(.x) > 1), as.list ) %>% flatten()
}
I was wondering if anybody knows a cleaner way of handling all three cases or, better yet, a function that does this already.
Without using any external packages
to_list <- function(...) as.list(unlist(list(...)))
str(to_list(1, 2, 3))
str(to_list(c(1, 2, 3)))
str(to_list(list(1, 2, 3)))
Another variation with purrr
to_list <- function(...) list(...) %>%
flatten
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.