我有一个存储不同数据类型和对象的列表:
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 按以下格式显示此列表:
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
如下:
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
现在打印的结果是:
> 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 改进了我原来的答案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)