Home > OS >  Neater representation of a list
Neater representation of a list

Time:11-27

Suppose I have function that returns a list

fun <- function()
{
    return(list(c(1,2,3), c(4,5,6), c(7,8,9)))
}

Now writing fun() gives me

[[1]]
[1] 1 2 3

[[2]]
[1] 4 5 6

[[3]]
[1] 7 8 9

But is there a way to get something like this?

list(c(1,2,3), 
     c(4,5,6), 
     c(7,8,9))

EDIT: how can I preserve both a nice output and a possibility of making operations on the list that is returned?

CodePudding user response:

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)

CodePudding user response:

this function returns exactly that - but I may have misunderstood

print_list <- function(x){
  cat("list(", paste(x, collapse="\n     "), ")", sep="")
}

print_list(fun())

Adding that to your existing function:

fun <- function(){
  cat("list(", paste(list(c(1,2,3), c(4,5,6), c(7,8,9)), collapse="\n     "), ")", sep="")
}

As noted in the comments, you could (if not bothered about the line breaks) use dput(fun())

  • Related