R:从列表对象创建自定义输出 [英] R: Create custom output from list object

查看:107
本文介绍了R:从列表对象创建自定义输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个存储不同数据类型和对象的列表:

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))

现在,我希望R以以下格式显示此列表:

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

有方便的方法吗?

推荐答案

如果要定期使用这种print,我将使用class如下:

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, ...)
}

如果您想了解有关泛型函数的更多信息,请参见 http://adv-r.had.co.nz/OO-essentials.html

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

现在打印结果为:

> 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

感谢Ananda Mahto和David Arenburg改善了我的原始答案.

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

这篇关于R:从列表对象创建自定义输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆