I think you're probably wanting a prettified version of dput:
fun <- function(x) {
text_con <- textConnection("output", "w")
dput(x, text_con)
close(text_con)
formatR::tidy_source(text = output, args.newline = TRUE, width = 40)
}
So for example:
mylist <- list(c(1,2,3), c(4,5,6), c(7,8,9))
fun(mylist)
#> list(
#> c(1, 2, 3),
#> c(4, 5, 6),
#> c(7, 8, 9)
#> )
EDIT
If you want a list to be printed in a particular way, but otherwise maintain all of the functionality of a list, it's probably best to create an S3 class with its own printing method:
special_list <- function(...) structure(list(...), class = "special_list")
as.special_list <- function(x) `class<-`(as.list(x), "special_list")
print.special_list <- function(x) {
text_con <- textConnection("output", "w")
dput(unclass(x), text_con)
close(text_con)
formatR::tidy_source(text = output, args.newline = TRUE, width = 40)
invisible(x)
}
Now you can create a special_list like this:
my_list <- special_list(a = c(1, 2, 3), b = letters[1:3])
my_list
#> list(
#> a = c(1, 2, 3),
#> b = c("a", "b", "c")
#> )
and it retains the functionality of any other list
my_list$a <- 2 * my_list$a
my_list
#> list(
#> a = c(2, 4, 6),
#> b = c("a", "b", "c")
#> )
It just means that you need to make a special_list instead of a normal list if you want to print a list this way. If you want to create a special_list from an existing list, you can do:
newlist <- list(a = 1:3)
newlist
#> $a
#> [1] 1 2 3
newlist <- as.special_list(newlist)
newlist
#> list(a = 1:3)