Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add dashed lines between elements of a list?

Tags:

r

I have a list like this:

x <- 1
y <- 2
z <- "something"
my_list <- list("x" = x, "y" = y, "z" = z)
> my_list
$x
[1] 1
$y
[1] 2
$z
"something"

in truth my list is very long including big text elements such that in output I can not recognise them easily. Therefore I want to put a dashed line after every element of the list in Output like

$x
[1] 1
-------------------------------------
$y
[1] 2
-------------------------------------
$z
[1] "something"
-------------------------------------
like image 818
Fateta Avatar asked Mar 03 '23 23:03

Fateta


2 Answers

Something like this could work.

mylistprint <- function(x){

    nn <- names(x)
    ll <- length(x)
    if (length(nn) != ll) {
      nn <- paste("Component", seq.int(ll))
      }
    for (i in seq_len(ll)) {
      cat(nn[i], ":\n")
      print(x[[i]])
      cat("\n")
      cat(strrep("-", 25))
      cat("\n")
    }
    invisible(x)
}

mylistprint(my_list)

The output of this would be:

x :
[1] 1

-------------------------
y :
[1] 2

-------------------------
z :
[1] "something"

-------------------------
like image 139
mfidino Avatar answered Mar 06 '23 11:03

mfidino


Using mapply
Probably a nicer way to do this is using mapply, or at least it is much shorter.

fun1 <- function(x,y) cat(paste0('$', x), y,strrep("-", 25), sep = '\n')
x <- mapply(fun1, names(my_list), my_list)

This prints:

$x
1
-------------------------
$y
2
-------------------------
$z
something
-------------------------

Single line

x <- mapply(function(x,y) cat(paste0('$', x), y,strrep("-", 25), sep = '\n'), names(my_list), my_list)

Wrap it in a function if you want

print.list <- function(list) {
  x <- mapply(function(x,y) cat(paste0('$', x), y,strrep("-", 25), sep = '\n'), names(list), list)
}
like image 26
CodeNoob Avatar answered Mar 06 '23 11:03

CodeNoob