2

さまざまなデータ型とオブジェクトを格納するリストがあります。

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

これを行う便利な方法はありますか?

4

1 に答える 1

7

この種のものを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 に感謝します。

于 2015-09-09T13:06:02.137 に答える