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"
-------------------------------------
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"
-------------------------
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With