-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathfields.R
94 lines (82 loc) · 2.09 KB
/
fields.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
fields <- function(...) {
that <- list(...)
class(that) <- "fields"
that
}
as.data.frame.fields <- function(x, ...) {
data.frame(
`Field name` = fields_names(x),
`Description` = fields_description(x),
`Width` = fields_widths(x),
`Type` = map_chr(fields_handlers(x), function(y) attr(y, "type")),
row.names = seq_along(x),
check.names = FALSE
)
}
print.fields <- function(x, ...) {
cat(paste(fields_names(x), collapse = ", "), "\n")
invisible(x)
}
fields_names <- function(fields) {
map_chr(fields, function(x) as.character(x))
}
fields_widths <- function(fields) {
map_int(fields, function(x) as.integer(attr(x, "width")))
}
fields_description <- function(fields) {
map_chr(fields, function(x) as.character(attr(x, "description")))
}
fields_handlers <- function(fields) {
handlers <- lapply(fields, function(x) attr(x, "handler"))
names(handlers) <- fields_names(fields)
handlers
}
field <- function(name, description, ...) {
if (missing(description)) {
attr(name, "description") <- ""
parms <- list(...)
} else {
if (is(description, "character")) {
attr(name, "description") <- description
parms <- list(...)
} else {
attr(name, "description") <- ""
parms <- list(description, ...)
warning(
"description invalid type: ",
paste(class(description), collapse = ", ")
)
}
}
classes <- lapply(parms, function(x) {
if (is(x, "width")) {
"width"
} else if (is(x, "handler")) {
"handler"
} else {
NULL
}
})
if (any(classes == "width")) {
attr(name, "width") <- parms[[which(classes == "width")[1]]]
} else {
attr(name, "width") <- 0
}
if (any(classes == "handler")) {
attr(name, "handler") <- parms[[which(classes == "handler")[1]]]
} else {
attr(name, "handler") <- pass_thru_handler()
}
class(name) <- "field"
name
}
print.parts <- function(x, ...) {
nx <- names(x)
for (ix in seq_along(nx)) {
dx <- dim(x[[ix]])
cat(sprintf(
"Part %2d: %s [%d obs. of %d variables]", ix, nx[ix], dx[1],
dx[2]
), "\n")
}
}