Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
2701 views
1
as.grade <- function(x)
2
{
3
if (inherits(x,"grade")) return(x)
4
if (match("sum",dimnames(x)[[2]],0) == 0) {
5
dx <- dim(x)
6
dnx <- dimnames(x)
7
if (length(dim(x)) == 2) {
8
if (length(dnx) != 2) dimnames(x) <- list(NULL, 1:dx[2])
9
tmp <- cbind(x,sum=0)
10
}
11
if (length(dim(x)) == 3) {
12
dimnames(x) <- NULL
13
tmp <- aperm(x,c(1,3,2))
14
dim(tmp) <- c(dim(tmp)[1]*dim(tmp)[3], dim(tmp)[2])
15
tmp <- cbind(tmp, sum=0)
16
dim(tmp) <- (dx + c(0,1,0))[c(1,3,2)]
17
tmp <- aperm(tmp,c(1,3,2))
18
if (length(dnx) != 3) dnx <- list(NULL, 1:dx[2], NULL)
19
dnx[[2]] <- c(dnx[[2]], "sum")
20
dimnames(tmp) <- dnx
21
}
22
if (length(dim(x)) > 3) stop("grade requires 2d or 3d")
23
}
24
x <- as.spread(tmp)
25
sum.col <- match("sum",dimnames(x)[[2]],0)
26
tmp.expr <- paste(
27
"x[,",
28
sum.col,
29
if (length(dim(x))==3) ",",
30
"] <- apply(x[,",
31
-sum.col,
32
if (length(dim(x))==3) ",",
33
"],",
34
deparse(if (length(dim(x))==3) c(1,3) else 1),
35
",sum)"
36
)
37
after(x)["sum"] <- parse(text=tmp.expr)
38
class(x) <- c("grade", class(x))
39
update.spread(x)
40
}
41
42
expr.rc.grade <- function(x, acpab)
43
{
44
if (sapply(acpab,nchar)[[2]] == 0) {
45
j <- -match("sum", dimnames(x)[[2]], 0)
46
acpab[2] <- j
47
}
48
expr.rc.default(x,acpab)
49
}
50
51