Skip to content

Commit 4d56121

Browse files
author
maechler
committed
[.table no longer loses other classes
git-svn-id: https://svn.r-project.org/R/trunk@88279 00db46b3-68df-0310-9c12-caf00c1e9a41
1 parent eb8a984 commit 4d56121

File tree

3 files changed

+20
-3
lines changed

3 files changed

+20
-3
lines changed

doc/NEWS.Rd

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,9 @@
110110
\item The \code{Pair(x,y)} construction in the formula interface to
111111
paired tests did not work with the \code{subset} argument, due to the
112112
absence of a \code{[.Pair} method, which has now been added.
113+
114+
\item Subsetting \code{"table"} objects keeps S3 classes more
115+
consistently, fixing \PR{18845}.
113116
}
114117
}
115118
}

src/library/base/R/table.R

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# File src/library/base/R/table.R
22
# Part of the R package, https://www.R-project.org
33
#
4-
# Copyright (C) 1995-2023 The R Core Team
4+
# Copyright (C) 1995-2025 The R Core Team
55
#
66
# This program is free software; you can redistribute it and/or modify
77
# it under the terms of the GNU General Public License as published by
@@ -319,12 +319,13 @@ margin.table <- marginSums
319319
## z
320320
## }
321321

322+
322323
`[.table` <-
323324
function(x, i, j, ..., drop = TRUE)
324325
{
325326
ret <- NextMethod()
326327
ldr <- length(dim(ret))
327-
if((ldr > 1L) || (ldr == length(dim(x))))
328-
class(ret) <- "table"
328+
if((ldr > 1L || ldr == length(dim(x))) && !inherits(ret, "table"))
329+
class(ret) <- if(any((cl <- oldClass(x)) == "table")) cl else c("table", cl)
329330
ret
330331
}

tests/reg-tests-1e.R

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1968,6 +1968,19 @@ stopifnot(identical(p1[2], substr(zp,1,1)),
19681968
## p2 gave warning too, and was the same as p1, erronously in R <= 4.5.0
19691969

19701970

1971+
## `[.table` consistency, PR#18845
1972+
T <- table(c(0:3,3:1,1:0), c(0:4,3:0)) ; class(T) <- c("myT", class(T))
1973+
T1 <- T[,3 , drop=FALSE]; dim(T1) <- length(T1); str(T1) # 1d table
1974+
stopifnot(exprs = {
1975+
identical(T, T[TRUE,]) # [..] had lost "myT" class
1976+
identical(T, T[,TRUE])
1977+
identical(T1, T1[TRUE]) # (worked before)
1978+
identical(class(T1), class(T)) # failed
1979+
identical(T1, T1[TRUE])
1980+
})
1981+
## subsetting only kept "table" class in R <= 4.5.x
1982+
1983+
19711984

19721985
## keep at end
19731986
rbind(last = proc.time() - .pt,

0 commit comments

Comments
 (0)