R: Create custom output from list object

人盡茶涼 提交于 2019-12-20 03:44:11

问题


I have a list that stores different data types and objects:

header <- "This is a header."
a <- 10
b <- 20
c <- 30
w <- 1:10
x <- 21:30
y <- 51:60
z <- 0:9

mylist <- list(header = header,
               const = list(a = a, b = b, c = c),
               data = data.frame(w,x,y,z))

Now I want R to display this list in the following format:

This is a header.

Values: a: 10    b: 20    c: 30

Data:         w  x  y z
          1   1 21 51 0
          2   2 22 52 1
          3   3 23 53 2
          4   4 24 54 3
          5   5 25 55 4
          6   6 26 56 5
          7   7 27 57 6
          8   8 28 58 7
          9   9 29 59 8
          10 10 30 60 9

Is there a convenient way to do this?


回答1:


If you want to use this kind of print regularly i would use a class as follows:

class(mylist) <- "myclass"

print.myclass <- function(x, ...){
  cat(x$header,"\n\n")
  cat("Values: ", sprintf("%s: %s", names(x$const), x$const), "\n\n")
  cat("Data:\n")
  print(x$data, ...)
}

If you want to learn more about generic function have a look at http://adv-r.had.co.nz/OO-essentials.html

Printing now results in:

> mylist #equal to print(mylist). Thats why we extended print with print.myclass
This is a header. 

Values:  a: 10 b: 20 c: 30 

Data:
    w  x  y z
1   1 21 51 0
2   2 22 52 1
3   3 23 53 2
4   4 24 54 3
5   5 25 55 4
6   6 26 56 5
7   7 27 57 6
8   8 28 58 7
9   9 29 59 8
10 10 30 60 9

Thanks to Ananda Mahto and David Arenburg for improving my original answer.



来源:https://stackoverflow.com/questions/32480094/r-create-custom-output-from-list-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!