1## Regression tests for which the printed output is the issue
2### _and_ must work (no Recommended packages, please)
3
4pdf("reg-tests-2.pdf", encoding = "ISOLatin1.enc")
5
6## force standard handling for data frames
7options(stringsAsFactors=FALSE) # R >= 4.0.0
8options(useFancyQuotes=FALSE)
9
10### moved from various .Rd files
11## abbreviate
12for(m in 1:5) {
13  cat("\n",m,":\n")
14  print(as.vector(abbreviate(state.name, minl=m)))
15}
16
17## apply
18x <- cbind(x1 = 3, x2 = c(4:1, 2:5))
19dimnames(x)[[1]] <- letters[1:8]
20apply(x,  2, summary) # 6 x n matrix
21apply(x,  1, quantile)# 5 x n matrix
22
23d.arr <- 2:5
24arr <- array(1:prod(d.arr), d.arr,
25         list(NULL,letters[1:d.arr[2]],NULL,paste("V",4+1:d.arr[4],sep="")))
26aa <- array(1:20,c(2,2,5))
27str(apply(aa[FALSE,,,drop=FALSE], 1, dim))# empty integer, `incorrect' dim.
28stopifnot(
29       apply(arr, 1:2, sum) == t(apply(arr, 2:1, sum)),
30       aa == apply(aa,2:3,function(x) x),
31       all.equal(apply(apply(aa,2:3, sum),2,sum),
32                 10+16*0:4, tolerance = 4*.Machine$double.eps)
33)
34marg <- list(1:2, 2:3, c(2,4), c(1,3), 2:4, 1:3, 1:4)
35for(m in marg) print(apply(arr, print(m), sum))
36for(m in marg) ## 75% of the time here was spent on the names
37  print(dim(apply(arr, print(m), quantile, names=FALSE)) == c(5,d.arr[m]))
38
39## Bessel
40nus <- c(0:5,10,20)
41
42x0 <- 2^(-20:10)
43plot(x0,x0, log='xy', ylab="", ylim=c(.1,1e60),type='n',
44     main = "Bessel Functions -Y_nu(x)  near 0\n log - log  scale")
45for(nu in sort(c(nus,nus+.5))) lines(x0, -besselY(x0,nu=nu), col = nu+2)
46legend(3,1e50, leg=paste("nu=", paste(nus,nus+.5, sep=",")), col=nus+2, lwd=1)
47
48x <- seq(3,500);yl <- c(-.3, .2)
49plot(x,x, ylim = yl, ylab="",type='n', main = "Bessel Functions  Y_nu(x)")
50for(nu in nus){xx <- x[x > .6*nu]; lines(xx,besselY(xx,nu=nu), col = nu+2)}
51legend(300,-.08, leg=paste("nu=",nus), col = nus+2, lwd=1)
52
53x <- seq(10,50000,by=10);yl <- c(-.1, .1)
54plot(x,x, ylim = yl, ylab="",type='n', main = "Bessel Functions  Y_nu(x)")
55for(nu in nus){xx <- x[x > .6*nu]; lines(xx,besselY(xx,nu=nu), col = nu+2)}
56summary(bY <- besselY(2,nu = nu <- seq(0,100,len=501)))
57which(bY >= 0)
58summary(bY <- besselY(2,nu = nu <- seq(3,300,len=51)))
59summary(bI <- besselI(x = x <- 10:700, 1))
60## end of moved from Bessel.Rd
61
62## data.frame
63set.seed(123)
64L3 <- LETTERS[1:3]
65d <- data.frame(cbind(x=1, y=1:10), fac = sample(L3, 10, replace=TRUE),
66                stringsAsFactors=TRUE)
67str(d)
68(d0  <- d[, FALSE]) # NULL dataframe with 10 rows
69(d.0 <- d[FALSE, ]) # <0 rows> dataframe  (3 cols)
70(d00 <- d0[FALSE,]) # NULL dataframe with 0 rows
71stopifnot(identical(d, cbind(d, d0)),
72          identical(d, cbind(d0, d)))
73stopifnot(identical(d, rbind(d,d.0)),
74          identical(d, rbind(d.0,d)),
75          identical(d, rbind(d00,d)),
76          identical(d, rbind(d,d00)))
77## Comments: failed before ver. 1.4.0
78
79## diag
80diag(array(1:4, dim=5))
81## test behaviour with 0 rows or columns
82diag(0)
83z <- matrix(0, 0, 4)
84diag(z)
85diag(z) <- numeric(0)
86z
87## end of moved from diag.Rd
88
89## format
90## handling of quotes
91zz <- data.frame(a=I("abc"), b=I("def\"gh"))
92format(zz)
93## " (E fontification)
94
95## printing more than 16 is platform-dependent
96for(i in c(1:5,10,15,16)) cat(i,":\t",format(pi,digits=i),"\n")
97
98p <- c(47,13,2,.1,.023,.0045, 1e-100)/1000
99format.pval(p)
100format.pval(p / 0.9)
101format.pval(p / 0.9, dig=3)
102## end of moved from format.Rd
103
104
105## is.finite
106x <- c(100,-1e-13,Inf,-Inf, NaN, pi, NA)
107x #  1.000000 -3.000000       Inf      -Inf        NA  3.141593        NA
108names(x) <- formatC(x, dig=3)
109is.finite(x)
110##-   100 -1e-13 Inf -Inf NaN 3.14 NA
111##-     T      T   .    .   .    T  .
112is.na(x)
113##-   100 -1e-13 Inf -Inf NaN 3.14 NA
114##-     .      .   .    .   T    .  T
115which(is.na(x) & !is.nan(x))# only 'NA': 7
116
117is.na(x) | is.finite(x)
118##-   100 -1e-13 Inf -Inf NaN 3.14 NA
119##-     T      T   .    .   T    T  T
120is.infinite(x)
121##-   100 -1e-13 Inf -Inf NaN 3.14 NA
122##-     .      .   T    T   .    .  .
123
124##-- either  finite or infinite  or  NA:
125all(is.na(x) != is.finite(x) | is.infinite(x)) # TRUE
126all(is.nan(x) != is.finite(x) | is.infinite(x)) # FALSE: have 'real' NA
127
128##--- Integer
129(ix <- structure(as.integer(x),names= names(x)))
130##-   100 -1e-13    Inf   -Inf    NaN   3.14     NA
131##-   100      0     NA     NA     NA      3     NA
132all(is.na(ix) != is.finite(ix) | is.infinite(ix)) # TRUE (still)
133
134storage.mode(ii <- -3:5)
135storage.mode(zm <- outer(ii,ii, FUN="*"))# integer
136storage.mode(zd <- outer(ii,ii, FUN="/"))# double
137range(zd, na.rm=TRUE)# -Inf  Inf
138zd[,ii==0]
139
140(storage.mode(print(1:1 / 0:0)))# Inf "double"
141(storage.mode(print(1:1 / 1:1)))# 1 "double"
142(storage.mode(print(1:1 + 1:1)))# 2 "integer"
143(storage.mode(print(2:2 * 2:2)))# 4 "integer"
144## end of moved from is.finite.Rd
145
146
147## kronecker
148fred <- matrix(1:12, 3, 4, dimnames=list(LETTERS[1:3], LETTERS[4:7]))
149bill <- c("happy" = 100, "sad" = 1000)
150kronecker(fred, bill, make.dimnames = TRUE)
151
152bill <- outer(bill, c("cat"=3, "dog"=4))
153kronecker(fred, bill, make.dimnames = TRUE)
154
155# dimnames are hard work: let's test them thoroughly
156
157dimnames(bill) <- NULL
158kronecker(fred, bill, make=TRUE)
159kronecker(bill, fred, make=TRUE)
160
161dim(bill) <- c(2, 2, 1)
162dimnames(bill) <- list(c("happy", "sad"), NULL, "")
163kronecker(fred, bill, make=TRUE)
164
165bill <- array(1:24, c(3, 4, 2))
166dimnames(bill) <- list(NULL, NULL, c("happy", "sad"))
167kronecker(bill, fred, make=TRUE)
168kronecker(fred, bill, make=TRUE)
169
170fred <- outer(fred, c("frequentist"=4, "bayesian"=4000))
171kronecker(fred, bill, make=TRUE)
172## end of moved from kronecker.Rd
173
174## merge
175authors <- data.frame(
176    surname = c("Tukey", "Venables", "Tierney", "Ripley", "McNeil"),
177    nationality = c("US", "Australia", "US", "UK", "Australia"),
178    deceased = c("yes", rep("no", 4)), stringsAsFactors=TRUE)
179books <- data.frame(
180    name = c("Tukey", "Venables", "Tierney",
181             "Ripley", "Ripley", "McNeil", "R Core"),
182    title = c("Exploratory Data Analysis",
183              "Modern Applied Statistics ...",
184              "LISP-STAT",
185              "Spatial Statistics", "Stochastic Simulation",
186              "Interactive Data Analysis",
187              "An Introduction to R"),
188    other.author = c(NA, "Ripley", NA, NA, NA, NA,
189		     "Venables & Smith"),
190	   stringsAsFactors=TRUE)
191b2 <- books; names(b2)[1] <- names(authors)[1]
192
193merge(authors, b2, all.x = TRUE)
194merge(authors, b2, all.y = TRUE)
195
196## empty d.f. :
197merge(authors, b2[7,])
198
199merge(authors, b2[7,], all.y = TRUE)
200merge(authors, b2[7,], all.x = TRUE)
201## end of moved from merge.Rd
202
203## NA
204is.na(c(1,NA))
205is.na(paste(c(1,NA)))
206is.na(list())# logical(0)
207ll <- list(pi,"C",NaN,Inf, 1:3, c(0,NA), NA)
208is.na (ll)
209lapply(ll, is.nan)  # is.nan no longer works on lists
210## end of moved from NA.Rd
211
212## is.na was returning unset values on nested lists
213ll <- list(list(1))
214for (i in 1:5) print(as.integer(is.na(ll)))
215
216## scale
217## test out NA handling
218tm <- matrix(c(2,1,0,1,0,NA,NA,NA,0), nrow=3)
219scale(tm, , FALSE)
220scale(tm)
221## end of moved from scale.Rd
222
223## tabulate
224tabulate(numeric(0))
225## end of moved from tabulate.Rd
226
227## ts
228# Ensure working arithmetic for 'ts' objects :
229z <- ts(matrix(1:900, 100, 3), start = c(1961, 1), frequency = 12)
230stopifnot(z == z)
231stopifnot(z-z == 0)
232
233ts(1:5, start=2, end=4) # truncate
234ts(1:5, start=3, end=17)# repeat
235## end of moved from ts.Rd
236
237### end of moved
238
239
240## PR 715 (Printing list elements w/attributes)
241##
242l <- list(a=10)
243attr(l$a, "xx") <- 23
244l
245## Comments:
246## should print as
247# $a:
248# [1] 10
249# attr($a, "xx"):
250# [1] 23
251
252## On the other hand
253m <- matrix(c(1, 2, 3, 0, 10, NA), 3, 2)
254na.omit(m)
255## should print as
256#      [,1] [,2]
257# [1,]    1    0
258# [2,]    2   10
259# attr(,"na.action")
260# [1] 3
261# attr(,"na.action")
262# [1] "omit"
263
264## and
265x <- 1
266attr(x, "foo") <- list(a="a")
267x
268## should print as
269# [1] 1
270# attr(,"foo")
271# attr(,"foo")$a
272# [1] "a"
273
274
275## PR 746 (printing of lists)
276##
277test.list <- list(A = list(formula=Y~X, subset=TRUE),
278                  B = list(formula=Y~X, subset=TRUE))
279
280test.list
281## Comments:
282## should print as
283# $A
284# $A$formula
285# Y ~ X
286#
287# $A$subset
288# [1] TRUE
289#
290#
291# $B
292# $B$formula
293# Y ~ X
294#
295# $B$subset
296# [1] TRUE
297
298## Marc Feldesman 2001-Feb-01.  Precision in summary.data.frame & *.matrix
299summary(attenu)
300summary(attenu, digits = 5)
301summary(data.matrix(attenu), digits = 5)# the same for matrix
302## Comments:
303## No difference between these in 1.2.1 and earlier
304set.seed(1)
305x <- c(round(runif(10), 2), 10000)
306summary(x)
307summary(data.frame(x))
308## Comments:
309## All entries show all 3 digits after the decimal point now.
310
311## Chong Gu 2001-Feb-16.  step on binomials
312detg1 <-
313structure(list(Temp = structure(c(2L, 1L, 2L, 1L, 2L, 1L, 2L,
314    1L, 2L, 1L, 2L, 1L), .Label = c("High", "Low"), class = "factor"),
315    M.user = structure(c(1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L,
316    1L, 2L, 2L), .Label = c("N", "Y"), class = "factor"),
317    Soft = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L),
318    .Label = c("Hard", "Medium", "Soft"), class = "factor"),
319    M = c(42, 30, 52, 43,
320    50, 23, 55, 47, 53, 27, 49, 29), X = c(68, 42, 37, 24, 66,
321    33, 47, 23, 63, 29, 57, 19)), .Names = c("Temp", "M.user",
322"Soft", "M", "X"), class = "data.frame", row.names = c("1", "3",
323"5", "7", "9", "11", "13", "15", "17", "19", "21", "23"))
324detg1.m0 <- glm(cbind(X,M)~1,binomial,detg1)
325detg1.m0
326step(detg1.m0,scope=list(upper=~M.user*Temp*Soft))
327
328## PR 829 (empty values in all.vars)
329## This example by Uwe Ligges <ligges@statistik.uni-dortmund.de>
330
331temp <- matrix(1:4, 2)
332all.vars(temp ~ 3) # OK
333all.vars(temp[1, ] ~ 3) # wrong in 1.2.1
334
335## 2001-Feb-22 from David Scott.
336## rank-deficient residuals in a manova model.
337gofX.df<-
338  structure(list(A = c(0.696706709347165, 0.362357754476673,
339-0.0291995223012888,
3400.696706709347165, 0.696706709347165, -0.0291995223012888, 0.696706709347165,
341-0.0291995223012888, 0.362357754476673, 0.696706709347165, -0.0291995223012888,
3420.362357754476673, -0.416146836547142, 0.362357754476673, 0.696706709347165,
3430.696706709347165, 0.362357754476673, -0.416146836547142, -0.0291995223012888,
344-0.416146836547142, 0.696706709347165, -0.416146836547142, 0.362357754476673,
345-0.0291995223012888), B = c(0.717356090899523, 0.932039085967226,
3460.999573603041505, 0.717356090899523, 0.717356090899523, 0.999573603041505,
3470.717356090899523, 0.999573603041505, 0.932039085967226, 0.717356090899523,
3480.999573603041505, 0.932039085967226, 0.909297426825682, 0.932039085967226,
3490.717356090899523, 0.717356090899523, 0.932039085967226, 0.909297426825682,
3500.999573603041505, 0.909297426825682, 0.717356090899523, 0.909297426825682,
3510.932039085967226, 0.999573603041505), C = c(-0.0291995223012888,
352-0.737393715541246, -0.998294775794753, -0.0291995223012888,
353-0.0291995223012888, -0.998294775794753, -0.0291995223012888,
354-0.998294775794753, -0.737393715541246, -0.0291995223012888,
355-0.998294775794753, -0.737393715541246, -0.653643620863612, -0.737393715541246,
356-0.0291995223012888, -0.0291995223012888, -0.737393715541246,
357-0.653643620863612, -0.998294775794753, -0.653643620863612,
358-0.0291995223012888,
359-0.653643620863612, -0.737393715541246, -0.998294775794753),
360    D = c(0.999573603041505, 0.67546318055115, -0.0583741434275801,
361    0.999573603041505, 0.999573603041505, -0.0583741434275801,
362    0.999573603041505, -0.0583741434275801, 0.67546318055115,
363    0.999573603041505, -0.0583741434275801, 0.67546318055115,
364    -0.756802495307928, 0.67546318055115, 0.999573603041505,
365    0.999573603041505, 0.67546318055115, -0.756802495307928,
366    -0.0583741434275801, -0.756802495307928, 0.999573603041505,
367    -0.756802495307928, 0.67546318055115, -0.0583741434275801
368    ), groups = structure(c(1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2,
369    2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3), class = "factor", .Label = c("1",
370    "2", "3"))), .Names = c("A", "B", "C", "D", "groups"), row.names = 1:24,
371            class = "data.frame")
372
373gofX.manova <- manova(formula = cbind(A, B, C, D) ~ groups, data = gofX.df)
374try(summary(gofX.manova))
375## should fail with an error message `residuals have rank 3 < 4'
376
377## Prior to 1.3.0 dist did not handle missing values, and the
378## internal C code was incorrectly scaling for missing values.
379z <- as.matrix(t(trees))
380z[1,1] <- z[2,2] <- z[3,3] <- z[2,4] <- NA
381dist(z, method="euclidean")
382dist(z, method="maximum")
383dist(z, method="manhattan")
384dist(z, method="canberra")
385
386## F. Tusell 2001-03-07.  printing kernels.
387kernel("daniell", m=5)
388kernel("modified.daniell", m=5)
389kernel("daniell", m=c(3,5,7))
390## fixed by patch from Adrian Trapletti 2001-03-08
391
392## Start new year (i.e. line) at Jan:
393(tt <- ts(1:10, start = c(1920,7), end = c(1921,4), freq = 12))
394cbind(tt, tt + 1)
395
396
397## PR 883 (cor(x,y) when is.null(y))
398try(cov(rnorm(10), NULL))
399try(cor(rnorm(10), NULL))
400## gave the variance and 1 respectively in 1.2.2.
401
402
403## PR 960 (format() of a character matrix converts to vector)
404## example from <John.Peters@tip.csiro.au>
405a <- matrix(c("axx","b","c","d","e","f","g","h"), nrow=2)
406format(a)
407format(a, justify="right")
408## lost dimensions in 1.2.3
409
410
411## PR 963
412res <- svd(rbind(1:7))## $v lost dimensions in 1.2.3
413if(res$u[1,1] < 0) {res$u <- -res$u; res$v <- -res$v}
414res
415
416
417## Make sure  on.exit() keeps being evaluated in the proper env [from PD]:
418## A more complete example:
419g1 <- function(fitted) { on.exit(remove(fitted)); return(function(foo) foo) }
420g2 <- function(fitted) { on.exit(remove(fitted));        function(foo) foo }
421f <- function(g) { fitted <- 1; h <- g(fitted); print(fitted)
422                   ls(envir=environment(h)) }
423f(g1)
424f(g2)
425
426f2 <- function()
427{
428  g.foo <- g1
429  g.bar <- g2
430  g <- function(x,...) UseMethod("g")
431  fitted <- 1; class(fitted) <- "foo"
432  h <- g(fitted); print(fitted); print(ls(envir=environment(h)))
433  fitted <- 1; class(fitted) <- "bar"
434  h <- g(fitted); print(fitted); print(ls(envir=environment(h)))
435  invisible(NULL)
436}
437f2()
438## The first case in f2() is broken in 1.3.0(-patched).
439
440## on.exit() consistency check from Luke:
441g <- function() as.environment(-1)
442f <- function(x) UseMethod("f")
443f.foo <- function(x) { on.exit(e <<- g()); NULL }
444f.bar <- function(x) { on.exit(e <<- g()); return(NULL) }
445f(structure(1,class = "foo"))
446ls(env = e)# only "x", i.e. *not* the GlobalEnv
447f(structure(1,class = "bar"))
448stopifnot("x" == ls(env = e))# as above; wrongly was .GlobalEnv in R 1.3.x
449
450
451## some tests that R supports logical variables in formulae
452## it coerced them to numeric prior to 1.4.0
453## they should appear like 2-level factors, following S
454
455oldCon <- options("contrasts")
456y <- rnorm(10)
457x <- rep(c(TRUE, FALSE), 5)
458model.matrix(y ~ x)
459lm(y ~ x)
460DF <- data.frame(x, y)
461lm(y ~ x, data=DF)
462options(contrasts=c("contr.helmert", "contr.poly"))
463model.matrix(y ~ x)
464lm(y ~ x, data=DF)
465z <- 1:10
466lm(y ~ x*z)
467lm(y ~ x*z - 1)
468options(oldCon)
469
470## diffinv, Adrian Trapletti, 2001-08-27
471x <- ts(1:10)
472diffinv(diff(x),xi=x[1])
473diffinv(diff(x,lag=1,differences=2),lag=1,differences=2,xi=x[1:2])
474## last had wrong start and end
475
476## PR#1072  (Reading Inf and NaN values)
477as.numeric(as.character(NaN))
478as.numeric(as.character(Inf))
479## were NA on Windows at least under 1.3.0.
480
481## PR#1092 (rowsum dimnames)
482rowsum(matrix(1:12, 3,4), c("Y","X","Y"))
483## rownames were 1,2 in <= 1.3.1.
484
485## PR#1115 (saving strings with ascii=TRUE)
486x <- y <- unlist(as.list(
487    parse(text=paste("\"\\", as.character(as.octmode(1:255)), "\"",sep=""))))
488save(x, ascii=TRUE, file=(fn <- tempfile(tmpdir = getwd())))
489load(fn)
490all(x==y)
491unlink(fn)
492## 1.3.1 had trouble with \
493
494
495## Some tests of sink() and connections()
496## capture all the output to a file.
497zz <- file("all.Rout", open="wt")
498sink(zz)
499sink(zz, type="message")
500try(log("a"))
501## back to the console
502sink(type="message")
503sink()
504try(log("a"))
505
506## capture all the output to a file.
507zz <- file("all.Rout", open="wt")
508sink(zz)
509sink(zz, type="message")
510try(log("a"))
511
512## bail out
513closeAllConnections()
514(foo <- showConnections())
515stopifnot(nrow(foo) == 0)
516try(log("a"))
517unlink("all.Rout")
518## many of these were untested before 1.4.0.
519
520
521## test mean() works on logical but not factor
522x <- c(TRUE, FALSE, TRUE, TRUE)
523mean(x)
524mean(as.factor(x))
525## last had confusing error message in 1.3.1.
526
527
528## Kurt Hornik 2001-Nov-13
529z <- table(x = 1:2, y = 1:2)
530z - 1
531unclass(z - 1)
532## lost object bit prior to 1.4.0, so printed class attribute.
533
534
535## PR#1226  (predict.mlm ignored newdata)
536ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)
537trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)
538group <- gl(2,10,20, labels = c("Ctl","Trt"))
539weight <- c(ctl, trt)
540data <- data.frame(weight, group)
541fit <- lm(cbind(w=weight, w2=weight^2) ~ group, data=data)
542predict(fit, newdata=data[1:2, ])
543## was 20 rows in R <= 1.4.0
544
545
546## Chong Gu 2002-Feb-8: `.' not expanded in drop1
547lab <- dimnames(HairEyeColor)
548HairEye <- cbind(expand.grid(Hair=lab$Hair, Eye=lab$Eye, Sex=lab$Sex,
549			     stringsAsFactors = TRUE),
550		 Fr = as.vector(HairEyeColor))
551HairEye.fit <- glm(Fr ~ . ^2, poisson, HairEye)
552drop1(HairEye.fit)
553## broken around 1.2.1 it seems.
554
555
556## PR#1329  (subscripting matrix lists)
557m <- list(a1=1:3, a2=4:6, a3=pi, a4=c("a","b","c"))
558dim(m) <- c(2,2)
559m
560m[,2]
561m[2,2]
562## 1.4.1 returned null components: the case was missing from a switch.
563
564m <- list(a1=1:3, a2=4:6, a3=pi, a4=c("a","b","c"))
565matrix(m, 2, 2)
566## 1.4.1 gave `Unimplemented feature in copyVector'
567
568x <- vector("list",6)
569dim(x) <- c(2,3)
570x[1,2] <- list(letters[10:11])
571x
572## 1.4.1 gave `incompatible types in subset assignment'
573
574
575## printing of matrix lists
576m <- list(as.integer(1), pi, 3+5i, "testit", TRUE, factor("foo"))
577dim(m) <- c(1, 6)
578m
579## prior to 1.5.0 had quotes for 2D case (but not kD, k > 2),
580## gave "numeric,1" etc, (even "numeric,1" for integers and factors)
581
582
583## ensure RNG is unaltered.
584for(type in c("Wichmann-Hill", "Marsaglia-Multicarry", "Super-Duper",
585              "Mersenne-Twister", "Knuth-TAOCP", "Knuth-TAOCP-2002"))
586{
587    set.seed(123, type)
588    print(RNGkind())
589    runif(100); print(runif(4))
590    set.seed(1000, type)
591    runif(100); print(runif(4))
592    set.seed(77, type)
593    runif(100); print(runif(4))
594}
595RNGkind(normal.kind = "Kinderman-Ramage")
596set.seed(123)
597RNGkind()
598rnorm(4)
599RNGkind(normal.kind = "Ahrens-Dieter")
600set.seed(123)
601RNGkind()
602rnorm(4)
603RNGkind(normal.kind = "Box-Muller")
604set.seed(123)
605RNGkind()
606rnorm(4)
607set.seed(123)
608runif(4)
609set.seed(123, "default")
610set.seed(123, "Marsaglia-Multicarry") ## Careful, not the default anymore
611runif(4)
612## last set.seed failed < 1.5.0.
613
614
615## merging, ggrothendieck@yifan.net, 2002-03-16
616d.df <- data.frame(x = 1:3, y = c("A","D","E"), z = c(6,9,10))
617merge(d.df[1,], d.df)
618## 1.4.1 got confused by inconsistencies in as.character
619
620
621## PR#1394 (levels<-.factor)
622f <- factor(c("a","b"))
623levels(f) <- list(C="C", A="a", B="b")
624f
625## was  [1] C A; Levels:  C A  in 1.4.1
626
627
628## NA levels in factors
629(x <- factor(c("a", "NA", "b"), exclude=NULL))
630## 1.4.1 had wrong order for levels
631is.na(x)[3] <- TRUE
632x
633## missing entry prints as <NA>
634
635
636## printing/formatting NA strings
637(x <- c("a", "NA", NA, "b"))
638print(x, quote = FALSE)
639paste(x)
640format(x)
641format(x, justify = "right")
642format(x, justify = "none")
643## not ideal.
644
645
646## print.ts problems  ggrothendieck@yifan.net on R-help, 2002-04-01
647x <- 1:20
648tt1 <- ts(x,start=c(1960,2), freq=12)
649tt2 <- ts(10+x,start=c(1960,2), freq=12)
650cbind(tt1, tt2)
651## 1.4.1 had `Jan 1961' as `NA 1961'
652## ...and 1.9.1 had it as `Jan 1960'!!
653
654## glm boundary bugs (related to PR#1331)
655x <- c(0.35, 0.64, 0.12, 1.66, 1.52, 0.23, -1.99, 0.42, 1.86, -0.02,
656       -1.64, -0.46, -0.1, 1.25, 0.37, 0.31, 1.11, 1.65, 0.33, 0.89,
657       -0.25, -0.87, -0.22, 0.71, -2.26, 0.77, -0.05, 0.32, -0.64, 0.39,
658       0.19, -1.62, 0.37, 0.02, 0.97, -2.62, 0.15, 1.55, -1.41, -2.35,
659       -0.43, 0.57, -0.66, -0.08, 0.02, 0.24, -0.33, -0.03, -1.13, 0.32,
660       1.55, 2.13, -0.1, -0.32, -0.67, 1.44, 0.04, -1.1, -0.95, -0.19,
661       -0.68, -0.43, -0.84, 0.69, -0.65, 0.71, 0.19, 0.45, 0.45, -1.19,
662       1.3, 0.14, -0.36, -0.5, -0.47, -1.31, -1.02, 1.17, 1.51, -0.33,
663       -0.01, -0.59, -0.28, -0.18, -1.07, 0.66, -0.71, 1.88, -0.14,
664       -0.19, 0.84, 0.44, 1.33, -0.2, -0.45, 1.46, 1, -1.02, 0.68, 0.84)
665y <- c(1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0,
666       0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1,
667       1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1,
668       0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1,
669       1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0)
670try(glm(y ~ x, family = poisson(identity)))
671## failed because start = NULL in 1.4.1
672## now gives useful error message
673glm(y ~ x, family = poisson(identity), start = c(1,0))
674## step reduction failed in 1.4.1
675set.seed(123)
676y <- rpois(100, pmax(3*x, 0))
677glm(y ~ x, family = poisson(identity), start = c(1,0))
678warnings()
679
680
681## extending char arrrays
682x <- y <- LETTERS[1:2]
683x[5] <- "C"
684length(y) <- 5
685x
686y
687## x was filled with "", y with NA in 1.5.0
688
689
690## formula with no intercept, 2002-07-22
691oldcon <- options(contrasts = c("contr.helmert", "contr.poly"))
692U <- gl(3, 6, 18, labels=letters[1:3])
693V <- gl(3, 2, 18, labels=letters[1:3])
694A <- rep(c(0, 1), 9)
695B <- rep(c(1, 0), 9)
696set.seed(1); y <- rnorm(18)
697terms(y ~ A:U + A:V - 1)
698lm(y ~ A:U + A:V - 1)$coefficients  # 1.5.1 used dummies coding for V
699lm(y ~ (A + B) : (U + V) - 1) # 1.5.1 used dummies coding for A:V but not B:V
700options(oldcon)
701## 1.5.1 miscomputed the first factor in the formula.
702
703
704## quantile extremes, MM 13 Apr 2000 and PR#1852
705(qq <- sapply(0:5, function(k) {
706    x <- c(rep(-Inf,k+1), 0:k, rep(Inf, k))
707    sapply(1:9, function(typ)
708           quantile(x, pr=(2:10)/10, type=typ))
709}, simplify="array"))
710x <- c(-Inf, -Inf, Inf, Inf)
711median(x)
712quantile(x)
713## 1.5.1 had -Inf not NaN in several places
714
715
716## NAs in matrix dimnames
717z <- matrix(1:9, 3, 3)
718dimnames(z) <- list(c("x", "y", NA), c(1, NA, 3))
719z
720## NAs in dimnames misaligned when printing in 1.5.1
721
722
723## weighted aov (PR#1930)
724r <- c(10,23,23,26,17,5,53,55,32,46,10,8,10,8,23,0,3,22,15,32,3)
725n <- c(39,62,81,51,39,6,74,72,51,79,13,16,30,28,45,4,12,41,30,51,7)
726trt <- factor(rep(1:4,c(5,6,5,5)))
727Y <- r/n
728z <- aov(Y ~ trt, weights=n)
729## 1.5.1 gave unweighted RSS
730
731
732## rbind (PR#2266)
733test <- as.data.frame(matrix(1:25, 5, 5))
734test1 <- matrix(-(1:10), 2, 5)
735rbind(test, test1)
736rbind(test1, test)
737## 1.6.1 treated matrix as a vector.
738
739
740## escapes in non-quoted printing
741x <- "\\abc\\"
742names(x) <- 1
743x
744print(x, quote=FALSE)
745## 1.6.2 had label misaligned
746
747
748## summary on data frames containing data frames (PR#1891)
749x <- data.frame(1:10)
750x$z <- data.frame(x=1:10,yyy=11:20)
751summary(x)
752## 1.6.2 had NULL labels on output with z columns stacked.
753
754
755## re-orderings in terms.formula (PR#2206)
756form <- formula(y ~ a + b:c + d + e + e:d)
757(tt <- terms(form))
758(tt2 <- terms(formula(tt)))
759stopifnot(identical(tt, tt2))
760terms(delete.response(tt))
761## both tt and tt2 re-ordered the formula < 1.7.0
762## now try with a dot
763terms(breaks ~ ., data = warpbreaks)
764terms(breaks ~ . - tension, data = warpbreaks)
765terms(breaks ~ . - tension, data = warpbreaks, simplify = TRUE)
766terms(breaks ~ . ^2, data = warpbreaks)
767terms(breaks ~ . ^2, data = warpbreaks, simplify = TRUE)
768## 1.6.2 expanded these formulae out as in simplify = TRUE
769
770
771## printing attributes (PR#2506)
772(x <- structure(1:4, other=as.factor(LETTERS[1:3])))
773## < 1.7.0 printed the codes of the factor attribute
774
775
776## add logical matrix replacement indexing for data frames
777TEMP <- data.frame(VAR1=c(1,2,3,4,5), VAR2=c(5,4,3,2,1), VAR3=c(1,1,1,1,NA))
778TEMP[,c(1,3)][TEMP[,c(1,3)]==1 & !is.na(TEMP[,c(1,3)])] < -10
779TEMP
780##
781
782## moved from reg-plot.R as exact output depends on rounding error
783## PR 390 (axis for small ranges)
784
785relrange <- function(x) {
786    ## The relative range in EPS units
787    r <- range(x)
788    diff(r)/max(abs(r))/.Machine$double.eps
789}
790
791x <- c(0.12345678912345678,
792       0.12345678912345679,
793       0.12345678912345676)
794# relrange(x) ## 1.0125, but depends on strtod
795plot(x) # `extra horizontal' ;  +- ok on Solaris; label off on Linux
796
797y <- c(0.9999563255363383973418,
798       0.9999563255363389524533,
799       0.9999563255363382863194)
800## The relative range number:
801# relrange(y) ## 3.000131, but depends on strtod
802plot(y)# once gave infinite loop on Solaris [TL];  y-axis too long
803
804## Comments: The whole issue was finally deferred to main/graphics.c l.1944
805##    error("relative range of values is too small to compute accurately");
806## which is not okay.
807
808set.seed(101)
809par(mfrow = c(3,3))
810for(j.fac in 1e-12* c(10, 1, .7, .3, .2, .1, .05, .03, .01)) {
811##           ====
812    #set.seed(101) # or don't
813    x <- pi + jitter(numeric(101), f = j.fac)
814    rrtxt <- paste("rel.range =", formatC(relrange(x), dig = 4),"* EPS")
815    cat("j.f = ", format(j.fac)," ;  ", rrtxt,"\n",sep="")
816    plot(x, type = "l", main = rrtxt)
817    cat("par(\"usr\")[3:4]:", formatC(par("usr")[3:4], wid = 10),"\n",
818        "par(\"yaxp\") :   ", formatC(par("yaxp"), wid = 10),"\n\n", sep="")
819}
820par(mfrow = c(1,1))
821## The warnings from inside GScale() will differ in their  relrange() ...
822## >> do sloppy testing
823## 2003-02-03 hopefully no more.  BDR
824## end of PR 390
825
826
827## scoping rules calling step inside a function
828"cement" <-
829    structure(list(x1 = c(7, 1, 11, 11, 7, 11, 3, 1, 2, 21, 1, 11, 10),
830                   x2 = c(26, 29, 56, 31, 52, 55, 71, 31, 54, 47, 40, 66, 68),
831                   x3 = c(6, 15, 8, 8, 6, 9, 17, 22, 18, 4, 23, 9, 8),
832                   x4 = c(60, 52, 20, 47, 33, 22, 6, 44, 22, 26, 34, 12, 12),
833                   y = c(78.5, 74.3, 104.3, 87.6, 95.9, 109.2, 102.7, 72.5,
834                   93.1, 115.9, 83.8, 113.3, 109.4)),
835              .Names = c("x1", "x2", "x3", "x4", "y"), class = "data.frame",
836              row.names = 1:13)
837teststep <- function(formula, data)
838{
839    d2 <- data
840    fit <- lm(formula, data=d2)
841    step(fit)
842}
843teststep(formula(y ~ .), cement)
844## failed in 1.6.2
845
846str(array(1))# not a scalar
847
848
849## na.print="" shouldn't apply to (dim)names!
850(tf <- table(ff <- factor(c(1:2,NA,2), exclude=NULL)))
851identical(levels(ff), dimnames(tf)[[1]])
852str(levels(ff))
853## not quite ok previous to 1.7.0
854
855
856## PR#3058  printing with na.print and right=TRUE
857a <- matrix( c(NA, "a", "b", "10",
858               NA, NA,  "d", "12",
859               NA, NA,  NA,  "14"),
860            byrow=T, ncol=4 )
861print(a, right=TRUE, na.print=" ")
862print(a, right=TRUE, na.print="----")
863## misaligned in 1.7.0
864
865
866## assigning factors to dimnames
867A <- matrix(1:4, 2)
868aa <- factor(letters[1:2])
869dimnames(A) <- list(aa, NULL)
870A
871dimnames(A)
872## 1.7.0 gave internal codes as display and dimnames()
873## 1.7.1beta gave NAs via dimnames()
874## 1.8.0 converts factors to character
875
876
877## wishlist PR#2776: aliased coefs in lm/glm
878set.seed(123)
879x2 <- x1 <- 1:10
880x3 <- 0.1*(1:10)^2
881y <- x1 + rnorm(10)
882(fit <- lm(y ~ x1 + x2 + x3))
883summary(fit, cor = TRUE)
884(fit <- glm(y ~ x1 + x2 + x3))
885summary(fit, cor = TRUE)
886## omitted silently in summary.glm < 1.8.0
887
888
889## list-like indexing of data frames with drop specified
890women["height"]
891women["height", drop = FALSE]  # same with a warning
892women["height", drop = TRUE]   # ditto
893women[,"height", drop = FALSE] # no warning
894women[,"height", drop = TRUE]  # a vector
895## second and third were interpreted as women["height", , drop] in 1.7.x
896
897
898## make.names
899make.names("")
900make.names(".aa")
901## was "X.aa" in 1.7.1
902make.names(".2")
903make.names(".2a") # not valid in R
904make.names(as.character(NA))
905##
906
907
908## strange names in data frames
909as.data.frame(list(row.names=17))  # 0 rows in 1.7.1
910aa <- data.frame(aa=1:3)
911aa[["row.names"]] <- 4:6
912aa # fine in 1.7.1
913A <- matrix(4:9, 3, 2)
914colnames(A) <- letters[1:2]
915aa[["row.names"]] <- A
916aa
917## wrong printed names in 1.7.1
918
919## assigning to NULL --- now consistently behaves as if assigning to list() !
920a <- NULL
921a[["a"]] <- 1
922a
923a <- NULL
924a[["a"]] <- "something"
925a
926a <- NULL
927a[["a"]] <- 1:3
928a
929## Last was an error in 1.7.1
930
931
932## examples of 0-rank models, some empty, some rank-deficient
933y <- rnorm(10)
934x <- rep(0, 10)
935(fit <- lm(y ~ 0))
936summary(fit)
937anova(fit)
938predict(fit)
939predict(fit, data.frame(x=x), se=TRUE)
940predict(fit, type="terms", se=TRUE)
941variable.names(fit) #should be empty
942model.matrix(fit)
943
944(fit <- lm(y ~ x + 0))
945summary(fit)
946anova(fit)
947predict(fit)
948predict(fit, data.frame(x=x), se=TRUE)
949predict(fit, type="terms", se=TRUE)
950variable.names(fit) #should be empty
951model.matrix(fit)
952
953(fit <- glm(y ~ 0))
954summary(fit)
955anova(fit)
956predict(fit)
957predict(fit, data.frame(x=x), se=TRUE)
958predict(fit, type="terms", se=TRUE)
959
960(fit <- glm(y ~ x + 0))
961summary(fit)
962anova(fit)
963predict(fit)
964predict(fit, data.frame(x=x), se=TRUE)
965predict(fit, type="terms", se=TRUE)
966## Lots of problems in 1.7.x
967
968
969## lm.influence on deficient lm models
970dat <- data.frame(y=rnorm(10), x1=1:10, x2=1:10, x3 = 0, wt=c(0,rep(1, 9)),
971                  row.names=letters[1:10])
972dat[3, 1] <- dat[4, 2] <- NA
973lm.influence(lm(y ~ x1 + x2, data=dat, weights=wt, na.action=na.omit))
974lm.influence(lm(y ~ x1 + x2, data=dat, weights=wt, na.action=na.exclude))
975lm.influence(lm(y ~ 0, data=dat, weights=wt, na.action=na.omit))
976print(width = 99,
977lm.influence(lm(y ~ 0, data=dat, weights=wt, na.action=na.exclude))
978) ; stopifnot(getOption("width") == 80)
979lm.influence(lm(y ~ 0 + x3, data=dat, weights=wt, na.action=na.omit))
980lm.influence(lm(y ~ 0 + x3, data=dat, weights=wt, na.action=na.exclude))
981lm.influence(lm(y ~ 0, data=dat, na.action=na.exclude))
982## last three misbehaved in 1.7.x, none had proper names.
983
984
985## length of results in ARMAacf when lag.max is used
986ARMAacf(ar=c(1.3,-0.6, -0.2, 0.1),lag.max=1) # was 4 in 1.7.1
987ARMAacf(ar=c(1.3,-0.6, -0.2, 0.1),lag.max=2)
988ARMAacf(ar=c(1.3,-0.6, -0.2, 0.1),lag.max=3)
989ARMAacf(ar=c(1.3,-0.6, -0.2, 0.1),lag.max=4)
990ARMAacf(ar=c(1.3,-0.6, -0.2, 0.1),lag.max=5) # failed in 1.7.1
991ARMAacf(ar=c(1.3,-0.6, -0.2, 0.1),lag.max=6)
992ARMAacf(ar=c(1.3,-0.6, -0.2, 0.1),lag.max=10)
993##
994
995
996## Indexing non-existent columns in a data frame
997x <- data.frame(a = 1, b = 2)
998try(x[c("a", "c")])
999try(x[, c("a", "c")])
1000try(x[1, c("a", "c")])
1001## Second succeeded, third gave uniformative error message in 1.7.x.
1002
1003
1004## methods(class = ) with namespaces, .Primitives etc (many missing in 1.7.x):
1005meth2gen <- function(cl)
1006    noquote(sub(paste("\\.",cl,"$",sep=""),"", c(.S3methods(class = cl))))
1007meth2gen("data.frame")
1008meth2gen("dendrogram")
1009## --> the output may need somewhat frequent updating..
1010
1011
1012## subsetting a 1D array lost the dimensions
1013x <- array(1:5, dim=c(5))
1014dim(x)
1015dim(x[, drop=TRUE])
1016dim(x[2:3])
1017dim(x[2])
1018dim(x[2, drop=FALSE])
1019dimnames(x) <- list(some=letters[1:5])
1020x[]
1021x[2:3]
1022x[2]
1023x[2, drop=FALSE]
1024## both dim and dimnames lost in 1.8.0
1025
1026
1027## print.dist() didn't show NA's prior to 1.8.1
1028x <- cbind(c(1,NA,2,3), c(NA,2,NA,1))
1029(d <- dist(x))
1030print(d, diag = TRUE)
1031##
1032
1033
1034## offsets in model terms where sometimes not deleted correctly
1035attributes(terms(~ a + b + a:b + offset(c)))[c("offset", "term.labels")]
1036attributes(terms(y ~ a + b + a:b + offset(c)))[c("offset", "term.labels")]
1037attributes(terms(~ offset(c) + a + b + a:b))[c("offset", "term.labels")]
1038attributes(terms(y ~ offset(c) + a + b + a:b))[c("offset", "term.labels")]
1039## errors prior to 1.8.1
1040
1041
1042## 0-level factors gave nonsensical answers in model.matrix
1043m <- model.frame(~x, data.frame(x=NA), na.action=na.pass)
1044model.matrix(~x, m)
1045lm.fit <- lm(y ~ x, data.frame(x=1:10, y=1:10))
1046try(predict(lm.fit, data.frame(x=NA)))
1047## wrong answers in 1.8.0, refused to run in 1.8.1
1048
1049
1050
1051## failure to print data frame containing arrays
1052## raised by John Fox on R-devel on 2004-01-08
1053y1 <- array(1:10, dim=10)
1054y2 <- array(1:30, dim=c(10,3), dimnames=list(NULL, letters[1:3]))
1055y3 <- array(1:40, dim=c(10,2,2),
1056            dimnames=list(NULL, letters[1:2], NULL))
1057data.frame(y=y1)
1058data.frame(y=y2)
1059data.frame(y=y3)
1060
1061as.data.frame(y1)
1062as.data.frame(y2)
1063as.data.frame(y3)
1064
1065X <- data.frame(x=1:10)
1066X$y <- y1
1067X
1068sapply(X, dim)
1069
1070X$y <- y2
1071X
1072sapply(X, dim)
1073
1074X$y <- y3
1075X
1076sapply(X, dim)
1077## The last one fails in S.
1078
1079## test of user hooks
1080for(id in c("A", "B")) {
1081    eval(substitute(
1082    {
1083setHook(packageEvent("stats4", "onLoad"),
1084        function(pkgname, ...) cat("onLoad", sQuote(pkgname), id, "\n"));
1085setHook(packageEvent("stats4", "attach"),
1086        function(pkgname, ...) cat("attach", sQuote(pkgname), id, "\n"));
1087setHook(packageEvent("stats4", "detach"),
1088        function(pkgname, ...) cat("detach", sQuote(pkgname), id, "\n"));
1089setHook(packageEvent("stats4", "onUnload"),
1090        function(pkgname, ...) cat("onUnload", sQuote(pkgname), id, "\n"))
1091    },
1092                    list(id=id)))
1093}
1094loadNamespace("stats4")
1095library("stats4")
1096detach("package:stats4")
1097unloadNamespace("stats4")
1098## Just tests
1099
1100
1101## rep(0-length-vector, length.out > 0)
1102rep(integer(0), length.out=0)
1103rep(integer(0), length.out=10)
1104typeof(.Last.value)
1105rep(logical(0), length.out=0)
1106rep(logical(0), length.out=10)
1107typeof(.Last.value)
1108rep(numeric(0), length.out=0)
1109rep(numeric(0), length.out=10)
1110typeof(.Last.value)
1111rep(character(0), length.out=0)
1112rep(character(0), length.out=10)
1113typeof(.Last.value)
1114rep(complex(0), length.out=0)
1115rep(complex(0), length.out=10)
1116typeof(.Last.value)
1117rep(list(), length.out=0)
1118rep(list(), length.out=10)
1119## always 0-length before 1.9.0
1120
1121
1122## supplying 0-length data to array and matrix
1123array(numeric(0), c(2, 2))
1124array(list(), c(2,2))
1125# worked < 1.8.0, error in 1.8.x
1126matrix(character(0), 1, 2)
1127matrix(integer(0), 1, 2)
1128matrix(logical(0), 1, 2)
1129matrix(numeric(0), 1, 2)
1130matrix(complex(0), 1, 2)
1131matrix(list(), 1, 2)
1132## did not work < 1.9.0
1133
1134
1135## S compatibility change in 1.9.0
1136rep(1:2, each=3, length=12)
1137## used to pad with NAs.
1138
1139
1140## PR#6510: aov() with error and -1
1141set.seed(1)
1142test.df <- data.frame (y=rnorm(8), a=gl(2,1,8), b=gl(2,3,8),c=gl(2,4,8))
1143aov(y ~ a + b + Error(c), data=test.df)
1144aov(y ~ a + b - 1 + Error(c), data=test.df)
1145## wrong assignment to strata labels < 1.9.0
1146## Note this is unbalanced and not a good example
1147
1148binom.test(c(800,10))# p-value < epsilon
1149
1150
1151## aov with a singular error model
1152rd <- c(16.53, 12.12, 10.04, 15.32, 12.33, 10.1, 17.09, 11.69, 11.81, 14.75,
1153        10.72, 8.79, 13.14, 9.79, 8.36, 15.62, 9.64, 8.72, 15.32,
1154        11.35, 8.52, 13.27, 9.74, 8.78, 13.16, 10.16, 8.4, 13.08, 9.66,
1155        8.16, 12.17, 9.13, 7.43, 13.28, 9.16, 7.92, 118.77, 78.83, 62.2,
1156        107.29, 73.79, 58.59, 118.9, 66.35, 53.12, 372.62, 245.39, 223.72,
1157        326.03, 232.67, 209.44, 297.55, 239.71, 223.8)
1158sample.df <- data.frame(dep.variable=rd,
1159                        subject=factor(rep(paste("subj",1:6, sep=""),each=9)),
1160                        f1=factor(rep(rep(c("f1","f2","f3"),each=6),3)),
1161                        f2=factor(rep(c("g1","g2","g3"),each=18))
1162)
1163sample.aov <- aov(dep.variable ~ f1 * f2 + Error(subject/(f1+f2)), data=sample.df)
1164sample.aov
1165summary(sample.aov)
1166sample.aov <- aov(dep.variable ~ f1 * f2 + Error(subject/(f2+f1)), data=sample.df)
1167sample.aov
1168summary(sample.aov)
1169## failed in 1.8.1
1170
1171
1172## PR#6645  stem() with near-constant values
1173stem(rep(1, 100))
1174stem(rep(0.1, 10))
1175stem(c(rep(1, 10), 1+1.e-8))
1176stem(c(rep(1, 10), 1+1.e-9))
1177stem(c(rep(1, 10), 1+1.e-10), atom=0) # integer-overflow is avoided.
1178##  had integer overflows in 1.8.1, and silly shifts of decimal point
1179
1180
1181## PR#6633 warnings with vector op matrix, and more
1182set.seed(1)
1183x1 <- rnorm(3)
1184y1 <- rnorm(4)
1185x1 * y1
1186x1 * as.matrix(y1) # no warning in 1.8.1
1187x1 * matrix(y1,2,2)# ditto
1188z1 <- x1 > 0
1189z2 <- y1 > 0
1190z1 & z2
1191z1 & as.matrix(z2) # no warning in 1.8.1
1192x1 < y1            # no warning in 1.8.1
1193x1 < as.matrix(y1) # ditto
1194##
1195
1196
1197## summary method for mle
1198library(stats4)
1199N <- c(rep(3:6, 3), 7,7, rep(8,6), 9,9, 10,12)# sample from Pois(lam = 7)
1200summary(mle(function(Lam = 1) -sum(dpois(N, Lam))))
1201## "Coefficients" was "NULL" in 1.9.0's "devel"
1202
1203
1204## PR#6656 terms.formula(simplify = TRUE) was losing offset terms
1205## successive offsets caused problems
1206df <- data.frame(x=1:4, y=sqrt( 1:4), z=c(2:4,1))
1207fit1 <- glm(y ~ offset(x) + z, data=df)
1208update(fit1, ". ~.")$call
1209## lost offset in 1.7.0 to 1.8.1
1210terms(y ~ offset(x) + offset(log(x)) + z, data=df)
1211## failed to remove second offset from formula in 1.8.1
1212terms(y ~ offset(x) + z - z, data=df, simplify = TRUE)
1213## first fix failed for models with no non-offset terms.
1214
1215
1216## only the first two were wrong up to 1.8.1:
12173:4 * 1e-100
12188:11* 1e-100
12191:2 * 1e-99
12201:2 * 1e+99
12218:11* 1e+99
12223:4 * 1e+100
1223##
1224
1225
1226## negative subscripts could be mixed with NAs
1227x <- 1:3
1228try(x[-c(1, NA)])
1229## worked on some platforms, segfaulted on others in 1.8.1
1230
1231
1232## vector 'border' (and no 'pch', 'cex' nor 'bg'):
1233boxplot(count ~ spray, data = InsectSprays, border=2:7)
1234## gave warnings in 1.9.0
1235
1236summary(as.Date(paste("2002-12", 26:31, sep="-")))
1237## printed all "2002.-12-29" in 1.9.1 {because digits was too small}
1238as.matrix(data.frame(d = as.POSIXct("2004-07-20")))
1239## gave a warning in 1.9.1
1240
1241
1242## Dump should quote when necessary (PR#6857)
1243x <- quote(b)
1244dump("x", "")
1245## doesn't quote b in 1.9.0
1246
1247
1248## some checks of indexing by character, used to test hashing code
1249x <- 1:26
1250names(x) <- letters
1251x[c("a", "aa", "aa")] <- 100:102
1252x
1253
1254x <- 1:26
1255names(x) <- rep("", 26)
1256x[c("a", "aa", "aa")] <- 100:102
1257x
1258##
1259
1260
1261## tests of raw type
1262# tests of logic operators
1263x <- "A test string"
1264(y <- charToRaw(x))
1265(xx <- c(y, as.raw(0), charToRaw("more")))
1266
1267!y
1268y & as.raw(15)
1269y | as.raw(128)
1270
1271# tests of binary read/write
1272zz <- file("testbin", "wb")
1273writeBin(xx, zz)
1274close(zz)
1275zz <- file("testbin", "rb")
1276(yy <- readBin(zz, "raw", 100))
1277seek(zz, 0, "start")
1278readBin(zz, "integer", n=100, size = 1) # read as small integers
1279seek(zz, 0, "start")
1280readBin(zz, "character", 100)  # is confused by embedded nul.
1281seek(zz, 0, "start")
1282readChar(zz, length(xx)) # truncates at embedded nul
1283seek(zz) # make sure current position is reported properly
1284close(zz)
1285unlink("testbin")
1286
1287# tests of ASCII read/write.
1288cat(xx, file="testascii")
1289scan("testascii", what=raw(0))
1290unlink("testascii")
1291##
1292
1293
1294## Example of prediction not from newdata as intended.
1295set.seed(1)
1296y <- rnorm(10)
1297x  <- cbind(1:10, sample(1:10)) # matrix
1298xt <- cbind(1:2,  3:4)
1299(lm1 <- lm(y ~ x))
1300predict(lm1, newdata = data.frame(x= xt))
1301## warns as from 2.0.0
1302
1303
1304## eval could alter a data.frame/list second argument
1305data(trees)
1306a <- trees
1307eval(quote({Girth[1]<-NA;Girth}),a)
1308a[1, ]
1309trees[1, ]
1310## both a and trees got altered in 1.9.1
1311
1312
1313## write.table did not apply qmethod to col.names (PR#7171)
1314x <- data.frame("test string with \"" = c("a \" and a '"), check.names=FALSE)
1315write.table(x)
1316write.table(x, qmethod = "double")
1317## Quote in col name was unescaped in 1.9.1.
1318
1319
1320## extensions to read.table
1321Mat <- matrix(c(1:3, letters[1:3], 1:3, LETTERS[1:3],
1322                c("2004-01-01", "2004-02-01", "2004-03-01"),
1323                c("2004-01-01 12:00", "2004-02-01 12:00", "2004-03-01 12:00")),
1324              3, 6)
1325foo <- tempfile(tmpdir = getwd())
1326write.table(Mat, foo, col.names = FALSE, row.names = FALSE)
1327read.table(foo, colClasses = c(NA, NA, "NULL", "character", "Date", "POSIXct"),
1328           stringsAsFactors=TRUE)
1329unlist(sapply(.Last.value, class))
1330read.table(foo, colClasses = c("factor",NA,"NULL","factor","Date","POSIXct"),
1331           stringsAsFactors=TRUE)
1332unlist(sapply(.Last.value, class))
1333read.table(foo, colClasses = c(V4="character"), stringsAsFactors=TRUE)
1334unlist(sapply(.Last.value, class))
1335unlink(foo)
1336## added in 2.0.0
1337
1338
1339## write.table with complex columns (PR#7260, in part)
1340write.table(data.frame(x = 0.5+1:4, y = 1:4 + 1.5i), file = "")
1341# printed all as complex in 2.0.0.
1342write.table(data.frame(x = 0.5+1:4, y = 1:4 + 1.5i), file = "", dec=",")
1343## used '.' not ',' in 2.0.0
1344
1345## splinefun() value test
1346(x <- seq(0,6, length=25))
1347mx <- sapply(c("fmm", "nat", "per"),
1348             function(m) splinefun(1:5, c(1,2,4,3,1), method = m)(x))
1349cbind(x,mx)
1350
1351
1352## infinite loop in read.fwf (PR#7350)
1353cat(file="test.txt", sep = "\n", "# comment 1", "1234567   # comment 2",
1354    "1 234567  # comment 3", "12345  67 # comment 4", "# comment 5")
1355read.fwf("test.txt", width=c(2,2,3), skip=1, n=4) # looped
1356read.fwf("test.txt", width=c(2,2,3), skip=1)      # 1 line short
1357read.fwf("test.txt", width=c(2,2,3), skip=0)
1358unlink("test.txt")
1359##
1360
1361
1362## split was not handling lists and raws
1363split(as.list(1:3), c(1,1,2))
1364(y <- charToRaw("A test string"))
1365(z <- split(y, rep(1:5, times=c(1,1,4,1,6))))
1366sapply(z, rawToChar)
1367## wrong results in 2.0.0
1368
1369
1370## tests of changed S3 implicit classes in 2.1.0
1371foo <- function(x, ...) UseMethod("foo")
1372foo.numeric <- function(x) cat("numeric arg\n")
1373foo(1:10)
1374foo(pi)
1375foo(matrix(1:10, 2, 5))
1376foo.integer <- function(x) cat("integer arg\n")
1377foo.double <- function(x) cat("double arg\n")
1378foo(1:10)
1379foo(pi)
1380foo(matrix(1:10, 2, 5))
1381##
1382
1383
1384## str() interpreted escape sequences prior to 2.1.0
1385x <- "ab\bc\ndef"
1386str(x)
1387str(x, vec.len=0)# failed in rev 32244
1388str(factor(x))
1389
1390x <- c("a", NA, "b")
1391factor(x)
1392factor(x, exclude="")
1393str(x)
1394str(factor(x))
1395str(factor(x, exclude=""))
1396##
1397
1398
1399## print.factor(quote=TRUE) was not quoting levels
1400x <- c("a", NA, "b", 'a " test') #" (comment for fontification)
1401factor(x)
1402factor(x, exclude="")
1403print(factor(x), quote=TRUE)
1404print(factor(x, exclude=""), quote=TRUE)
1405## last two printed levels differently from values in 2.0.1
1406
1407
1408## write.table in marginal cases
1409x <- matrix(, 3, 0)
1410write.table(x) # 3 rows
1411write.table(x, row.names=FALSE)
1412# note: scan and read.table won't read this as they take empty fields as NA
1413## was 1 row in 2.0.1
1414
1415
1416## More tests of write.table
1417x <- list(a=1, b=1:2, c=3:4, d=5)
1418dim(x) <- c(2,2)
1419x
1420write.table(x)
1421
1422x1 <- data.frame(a=1:2, b=I(matrix(LETTERS[1:4], 2, 2)), c = c("(i)", "(ii)"))
1423x1
1424write.table(x1) # In 2.0.1 had 3 headers, 4 cols
1425write.table(x1, quote=c(2,3,4))
1426
1427x2 <- data.frame(a=1:2, b=I(list(a=1, b=2)))
1428x2
1429write.table(x2)
1430
1431x3 <- seq(as.Date("2005-01-01"), len=6, by="day")
1432x4 <- data.frame(x=1:6, y=x3)
1433dim(x3) <- c(2,3)
1434x3
1435write.table(x3) # matrix, so loses class
1436x4
1437write.table(x4) # preserves class, does not quote
1438##
1439
1440
1441## Problem with earlier regexp code spotted by KH
1442grep("(.*s){2}", "Arkansas", v = TRUE)
1443grep("(.*s){3}", "Arkansas", v = TRUE)
1444grep("(.*s){3}", state.name, v = TRUE)
1445## Thought Arkansas had 3 s's.
1446
1447
1448## Replacing part of a non-existent column could create a short column.
1449xx<- data.frame(a=1:4, b=letters[1:4])
1450xx[2:3, "c"] <- 2:3
1451## gave short column in R < 2.1.0.
1452
1453
1454## add1/drop1 could give misleading results if missing values were involved
1455y <- rnorm(1:20)
1456x <- 1:20; x[10] <- NA
1457x2 <- runif(20); x2[20] <- NA
1458fit <- lm(y ~ x)
1459drop1(fit)
1460res <-  try(stats:::drop1.default(fit))
1461stopifnot(inherits(res, "try-error"))
1462add1(fit, ~ . +x2)
1463res <-  try(stats:::add1.default(fit, ~ . +x2))
1464stopifnot(inherits(res, "try-error"))
1465## 2.0.1 ran and gave incorrect answers.
1466
1467
1468## (PR#7789) escaped quotes in the first five lines for read.table
1469tf <- tempfile(tmpdir = getwd())
1470x <- c("6 'TV2  Shortland Street'",
1471       "2 'I don\\\'t watch TV at 7'",
1472       "1 'I\\\'m not bothered, whatever that looks good'",
1473       "2 'I channel surf'")
1474writeLines(x, tf)
1475read.table(tf)
1476x <- c("6 'TV2  Shortland Street'",
1477       "2 'I don''t watch TV at 7'",
1478       "1 'I''m not bothered, whatever that looks good'",
1479       "2 'I channel surf'")
1480writeLines(x, tf)
1481read.table(tf, sep=" ")
1482unlink(tf)
1483## mangled in 2.0.1
1484
1485
1486## (PR#7802) printCoefmat(signif.legend =FALSE) failed
1487set.seed(123)
1488cmat <- cbind(rnorm(3, 10), sqrt(rchisq(3, 12)))
1489cmat <- cbind(cmat, cmat[,1]/cmat[,2])
1490cmat <- cbind(cmat, 2*pnorm(-cmat[,3]))
1491colnames(cmat) <- c("Estimate", "Std.Err", "Z value", "Pr(>z)")
1492printCoefmat(cmat, signif.stars = TRUE)
1493printCoefmat(cmat, signif.stars = TRUE, signif.legend = FALSE)
1494# no stars, so no legend
1495printCoefmat(cmat, signif.stars = FALSE)
1496printCoefmat(cmat, signif.stars = TRUE, signif.legend = TRUE)
1497## did not work in 2.1.0
1498
1499
1500## PR#7824 subscripting an array by a matrix
1501x <- matrix(1:6, ncol=2)
1502x[rbind(c(1,1), c(2,2))]
1503x[rbind(c(1,1), c(2,2), c(0,1))]
1504x[rbind(c(1,1), c(2,2), c(0,0))]
1505x[rbind(c(1,1), c(2,2), c(0,2))]
1506x[rbind(c(1,1), c(2,2), c(0,3))]
1507x[rbind(c(1,1), c(2,2), c(1,0))]
1508x[rbind(c(1,1), c(2,2), c(2,0))]
1509x[rbind(c(1,1), c(2,2), c(3,0))]
1510x[rbind(c(1,0), c(0,2), c(3,0))]
1511x[rbind(c(1,0), c(0,0), c(3,0))]
1512x[rbind(c(1,1), c(2,2), c(1,2))]
1513x[rbind(c(1,1), c(2,NA), c(1,2))]
1514x[rbind(c(1,0), c(2,NA), c(1,2))]
1515try(x[rbind(c(1,1), c(2,2), c(-1,2))])
1516try(x[rbind(c(1,1), c(2,2), c(-2,2))])
1517try(x[rbind(c(1,1), c(2,2), c(-3,2))])
1518try(x[rbind(c(1,1), c(2,2), c(-4,2))])
1519try(x[rbind(c(1,1), c(2,2), c(-1,-1))])
1520try(x[rbind(c(1,1,1), c(2,2,2))])
1521
1522# verify that range checks are applied to negative indices
1523x <- matrix(1:6, ncol=3)
1524try(x[rbind(c(1,1), c(2,2), c(-3,3))])
1525try(x[rbind(c(1,1), c(2,2), c(-4,3))])
1526## generally allowed in 2.1.0.
1527
1528
1529## printing RAW matrices/arrays was not implemented
1530s <- sapply(0:7, function(i) rawShift(charToRaw("my text"),i))
1531s
1532dim(s) <- c(7,4,2)
1533s
1534## empty < 2.1.1
1535
1536
1537## interpretation of '.' directly by model.matrix
1538dd <- data.frame(a = gl(3,4), b = gl(4,1,12))
1539model.matrix(~ .^2, data = dd)
1540## lost ^2 in 2.1.1
1541
1542
1543## add1.lm and drop.lm did not know about offsets (PR#8049)
1544set.seed(2)
1545y <- rnorm(10)
1546z <- 1:10
1547lm0 <- lm(y ~ 1)
1548lm1 <- lm(y ~ 1, offset = 1:10)
1549lm2 <- lm(y ~ z, offset = 1:10)
1550
1551add1(lm0, scope = ~ z)
1552anova(lm1, lm2)
1553add1(lm1, scope = ~ z)
1554drop1(lm2)
1555## Last two ignored the offset in 2.1.1
1556
1557
1558## tests of raw conversion
1559as.raw(1234)
1560as.raw(list(a=1234))
1561## 2.1.1: spurious and missing messages, wrong result for second.
1562
1563
1564### end of tests added in 2.1.1 patched ###
1565
1566
1567## Tests of logical matrix indexing with NAs
1568df1 <- data.frame(a = c(NA, 0, 3, 4)); m1 <- as.matrix(df1)
1569df2 <- data.frame(a = c(NA, 0, 0, 4)); m2 <- as.matrix(df2)
1570df1[df1 == 0] <- 2; df1
1571m1[m1 == 0] <- 2;   m1
1572df2[df2 == 0] <- 2; df2  # not allowed in 2.{0,1}.z
1573m2[m2 == 0] <- 2;   m2
1574df1[df1 == 2] # this is first coerced to a matrix, and drops to a vector
1575df3 <- data.frame(a=1:2, b=2:3)
1576df3[df3 == 2]            # had spurious names
1577# but not allowed
1578## (modified to make printed result the same whether numeric() is
1579##  compiled or interpreted)
1580## try(df2[df2 == 2] <- 1:2)
1581## try(m2[m2 == 2] <- 1:2)
1582tryCatch(df2[df2 == 2] <- 1:2,
1583         error = function(e) paste("Error:", conditionMessage(e)))
1584tryCatch(m2[m2 == 2] <- 1:2,
1585         error = function(e) paste("Error:", conditionMessage(e)))
1586##
1587
1588
1589## vector indexing of matrices: issue is when rownames are used
1590# 1D array
1591m1 <- c(0,1,2,0)
1592dim(m1) <- 4
1593dimnames(m1) <- list(1:4)
1594m1[m1 == 0]                        # has rownames
1595m1[which(m1 == 0)]                 # has rownames
1596m1[which(m1 == 0, arr.ind = TRUE)] # no names < 2.2.0 (side effect of PR#937)
1597
1598# 2D array with 2 cols
1599m2 <- as.matrix(data.frame(a=c(0,1,2,0), b=0:3))
1600m2[m2 == 0]                        # a vector, had names < 2.2.0
1601m2[which(m2 == 0)]                 # a vector, had names < 2.2.0
1602m2[which(m2 == 0, arr.ind = TRUE)] # no names (PR#937)
1603
1604# 2D array with one col: could use rownames but do not.
1605m21 <- m2[, 1, drop = FALSE]
1606m21[m21 == 0]
1607m21[which(m21 == 0)]
1608m21[which(m21 == 0, arr.ind = TRUE)]
1609## not consistent < 2.2.0: S never gives names
1610
1611
1612## tests of indexing as quoted in Extract.Rd
1613x <- NULL
1614x$foo <- 2
1615x # now, a list
1616x <- NULL
1617x[[2]] <- pi
1618x # now, a list, too
1619x <- NULL
1620x[[1]] <- 1:3
1621x # list
1622##
1623
1624
1625## printing of a kernel:
1626kernel(1)
1627## printed wrongly in R <= 2.1.1
1628
1629
1630## using NULL as a replacement value
1631DF <- data.frame(A=1:2, B=3:4)
1632try(DF[2, 1:3] <- NULL)
1633## wrong error message in R < 2.2.0
1634
1635
1636## tests of signif
1637ob <- 0:9 * 2000
1638print(signif(ob, 3), digits=17) # had rounding error in 2.1.1
1639signif(1.2347e-305, 4)
1640signif(1.2347e-306, 4)  # only 3 digits in 2.1.1
1641signif(1.2347e-307, 4)
1642##
1643
1644### end of tests added in 2.2.0 patched ###
1645
1646
1647## printing lists with NA names
1648A <- list(1, 2)
1649names(A) <- c("NA", NA)
1650A
1651## both printed as "NA" in 2.2.0
1652
1653
1654## subscripting with both NA and "NA" names
1655x <- 1:4
1656names(x) <- c(NA, "NA", "a", "")
1657x[names(x)]
1658## 2.2.0 had the second matching the first.
1659lx <- as.list(x)
1660lx[[as.character(NA)]]
1661lx[as.character(NA)]
1662## 2.2.0 had both matching element 1
1663
1664
1665## data frame replacement subscripting
1666# Charles C. Berry, R-devel, 2005-10-26
1667a.frame <- data.frame( x=letters[1:5] )
1668a.frame[ 2:5, "y" ] <- letters[2:5]
1669a.frame  # added rows 1:4
1670# and adding and replacing matrices failed
1671a.frame[ ,"y" ] <- matrix(1:10, 5, 2)
1672a.frame
1673a.frame[3:5 ,"y" ] <- matrix(1:6, 3, 2)
1674a.frame
1675a.frame <- data.frame( x=letters[1:5] )
1676a.frame[3:5 ,"y" ] <- matrix(1:6, 3, 2)
1677a.frame
1678## failed/wrong ans in 2.2.0
1679
1680
1681### end of tests added in 2.2.0 patched ###
1682
1683
1684## test of fix of trivial warning PR#8252
1685pairs(iris[1:4], oma=rep(3,4))
1686## warned in 2.2.0 only
1687
1688
1689## str(<dendrogram>)
1690dend <- as.dendrogram(hclust(dist(USArrests), "ave")) # "print()" method
1691dend2 <- cut(dend, h=70)
1692str(dend2$upper)
1693## {{for Emacs: `}}  gave much too many spaces in 2.2.[01]
1694
1695
1696## formatC on Windows (PR#8337)
1697xx  <- pi * 10^(-5:4)
1698cbind(formatC(xx, wid = 9))
1699cbind(formatC(xx, wid = 9, flag = "-"))
1700cbind(formatC(xx, wid = 9, flag = "0"))
1701## extra space on 2.2.1
1702
1703
1704## an impossible glm fit
1705success <- c(13,12,11,14,14,11,13,11,12)
1706failure <- c(0,0,0,0,0,0,0,2,2)
1707predictor <- c(0, 5^(0:7))
1708try(glm(cbind(success,failure) ~ 0+predictor, family = binomial(link="log")))
1709# no coefficient is possible as the first case will have mu = 1
1710## 2.2.1 gave a subscript out of range warning instead.
1711
1712
1713## error message from solve (PR#8494)
1714temp <- diag(1, 5)[, 1:4]
1715rownames(temp) <- as.character(1:5)
1716colnames(temp) <- as.character(1:4)
1717try(solve(temp))
1718# also complex
1719try(solve(temp+0i))
1720# and non-comformant systems
1721try(solve(temp, diag(3)))
1722## gave errors from rownames<- in 2.2.1
1723
1724
1725## PR#8462 terms.formula(simplify = TRUE) needs parentheses.
1726update.formula (Reaction ~ Days + (Days | Subject), . ~ . + I(Days^2))
1727## < 2.3.0 dropped parens on second term.
1728
1729
1730## PR#8528: errors in the post-2.1.0 pgamma
1731pgamma(seq(0.75, 1.25, by=0.05)*1e100, shape = 1e100, log=TRUE)
1732pgamma(seq(0.75, 1.25, by=0.05)*1e100, shape = 1e100, log=TRUE, lower=FALSE)
1733pgamma(c(1-1e-10, 1+1e-10)*1e100, shape = 1e100)
1734pgamma(0.9*1e25, 1e25, log=TRUE)
1735## were NaN, -Inf etc in 2.2.1.
1736
1737
1738## + for POSIXt objects was non-commutative
1739# SPSS-style dates
1740c(10485849600,10477641600,10561104000,10562745600)+ISOdate(1582,10,14)
1741## was in the local time zone in 2.2.1.
1742
1743
1744## Limiting lines on deparse (wishlist PR#8638)
1745op <- options(deparse.max.lines = 3)
1746f <- function(...) browser()
1747do.call(f, mtcars)
1748c
1749
1750op <- c(op, options(error = expression(NULL)))
1751f <- function(...) stop()
1752do.call(f, mtcars)
1753traceback()
1754
1755## Debugger can handle a function that has a single function call as its body
1756g <- function(fun) fun(1)
1757debug(g)
1758g(function(x) x+1)
1759
1760options(op)
1761## unlimited < 2.3.0
1762
1763
1764## row names in as.table (PR#8652)
1765as.table(matrix(1:60, ncol=2))
1766## rows past 26 had NA row names
1767
1768
1769## summary on a glm with zero weights and estimated dispersion (PR#8720)
1770y <- rnorm(10)
1771x <- 1:10
1772w <- c(rep(1,9), 0)
1773summary(glm(y ~ x, weights = w))
1774summary(glm(y ~ x, subset = w > 0))
1775## has NA dispersion in 2.2.1
1776
1777
1778## substitute was losing "..." after r37269
1779yaa <- function(...) substitute(list(...))
1780yaa(foo(...))
1781## and wasn't substituting after "..."
1782substitute(list(..., x), list(x=1))
1783## fixed for 2.3.0
1784
1785
1786## uniroot never warned (PR#8750)
1787ff <- function(x) (x-pi)^3
1788uniroot(ff, c(-10,10), maxiter=10)
1789## should warn, did not < 2.3.0
1790
1791
1792### end of tests added in 2.3.0 ###
1793
1794
1795## prod etc on empty lists and raw vectors
1796try(min(list()))
1797try(max(list()))
1798try(sum(list()))
1799try(prod(list()))
1800try(min(raw()))
1801try(max(raw()))
1802try(sum(raw()))
1803try(prod(raw()))
1804## Inf, -Inf, list(NULL) etc in 2.2.1
1805
1806r <- hist(rnorm(100), plot = FALSE, breaks = 12,
1807          ## arguments which don't make sense for plot=FALSE - give a warning:
1808          xlab = "N(0,1)", col = "blue")
1809## gave no warning in 2.3.0 and earlier
1810
1811
1812## rbind.data.frame on permuted cols (PR#8868)
1813d1 <- data.frame(x=1:10, y=letters[1:10], z=1:10)
1814d2 <- data.frame(y=LETTERS[1:5], z=5:1, x=7:11)
1815rbind(d1, d2)
1816# got factor y  wrong in 2.3.0
1817# and failed with duplicated col names.
1818d1 <- data.frame(x=1:2, y=5:6, x=8:9, check.names=FALSE)
1819d2 <- data.frame(x=3:4, x=-(1:2), y=8:9, check.names=FALSE)
1820rbind(d1, d2)
1821## corrupt in 2.3.0
1822
1823
1824## sort.list on complex vectors was unimplemented prior to 2.4.0
1825x <- rep(2:1, c(2, 2)) + 1i*c(4, 1, 2, 3)
1826(o <- sort.list(x))
1827x[o]
1828sort(x)  # for a cross-check
1829##
1830
1831
1832## PR#9044 write.table(quote=TRUE, row.names=FALSE) did not quote column names
1833m <- matrix(1:9, nrow=3, dimnames=list(c("A","B","C"),  c("I","II","III")))
1834write.table(m)
1835write.table(m, col.names=FALSE)
1836write.table(m, row.names=FALSE)
1837# wrong < 2.3.1 patched.
1838write.table(m, quote=FALSE)
1839write.table(m, col.names=FALSE, quote=FALSE)
1840write.table(m, row.names=FALSE, quote=FALSE)
1841d <- as.data.frame(m)
1842write.table(d)
1843write.table(d, col.names=FALSE)
1844write.table(d, row.names=FALSE)
1845write.table(d, quote=FALSE)
1846write.table(d, col.names=FALSE, quote=FALSE)
1847write.table(d, row.names=FALSE, quote=FALSE)
1848write.table(m, quote=numeric(0)) # not the same as FALSE
1849##
1850
1851
1852## removing variable from baseenv
1853try(remove("ls", envir=baseenv()))
1854try(remove("ls", envir=asNamespace("base")))
1855## no message in 2.3.1
1856
1857
1858## tests of behaviour of factors
1859(x <- factor(LETTERS[1:5])[2:4])
1860x[2]
1861x[[2]]
1862stopifnot(identical(x[2], x[[2]]))
1863as.list(x)
1864(xx <- unlist(as.list(x)))
1865stopifnot(identical(x, xx))
1866as.vector(x, "list")
1867(sx <- sapply(x, function(.).))
1868stopifnot(identical(x, sx))
1869## changed in 2.4.0
1870
1871
1872## as.character on a factor with "NA" level
1873as.character(as.factor(c("AB", "CD", NA)))
1874as.character(as.factor(c("NA", "CD", NA)))  # use <NA> is 2.3.x
1875as.vector(as.factor(c("NA", "CD", NA)))     # but this did not
1876## used <NA> before
1877
1878
1879## [ on a zero-column data frame, names of such
1880data.frame()[FALSE]
1881names(data.frame())
1882# gave NULL names and hence spurious warning.
1883
1884
1885## residuals from zero-weight glm fits
1886d.AD <- data.frame(treatment = gl(3,3), outcome = gl(3,1,9),
1887                   counts = c(18,17,15,20,10,20,25,13,12))
1888fit <- glm(counts ~ outcome + treatment, family = poisson,
1889           data = d.AD, weights = c(0, rep(1,8)))
1890print(residuals(fit, type="working"),
1891      width = 37) # first was NA < 2.4.0 //  using new 'width'
1892## working residuals were NA for zero-weight cases.
1893fit2 <- glm(counts ~ outcome + treatment, family = poisson,
1894            data = d.AD, weights = c(0, rep(1,8)), y = FALSE)
1895for(z in c("response", "working", "deviance", "pearson"))
1896    stopifnot(all.equal(residuals(fit, type=z), residuals(fit2, type=z),
1897                        scale = 1, tolerance = 1e-10))
1898
1899## apply on arrays with zero extents
1900## Robin Hankin, R-help, 2006-02-13
1901A <- array(0, c(3, 0, 4))
1902dimnames(A) <- list(D1 = letters[1:3], D2 = NULL, D3 = LETTERS[1:4])
1903f <- function(x) 5
1904apply(A, 1:2, f)
1905apply(A, 1, f)
1906apply(A, 2, f)
1907## dropped dims in 2.3.1
1908
1909
1910## print a factor with names
1911structure(factor(1:4), names = letters[1:4])
1912## dropped names < 2.4.0
1913
1914
1915## some tests of factor matrices
1916A <- factor(7:12)
1917dim(A) <- c(2, 3)
1918A
1919str(A)
1920A[, 1:2]
1921A[, 1:2, drop=TRUE]
1922A[1,1] <- "9"
1923A
1924## misbehaved < 2.4.0
1925
1926
1927## [dpqr]t with vector ncp
1928nc <- c(0, 0.0001, 1)
1929dt(1.8, 10, nc)
1930pt(1.8, 10, nc)
1931qt(0.95, 10, nc)
1932## gave warnings in 2.3.1, short answer for qt.
1933dt(1.8, 10, -nc[-1])
1934pt(1.8, 10, -nc[-1])
1935qt(0.95, 10, -nc[-1])
1936## qt in 2.3.1 did not allow negative ncp.
1937
1938
1939## merge() used to insert row names as factor, not character, so
1940## sorting was unexpected.
1941A <- data.frame(a = 1:4)
1942row.names(A) <- c("2002-11-15", "2002-12-15", "2003-01-15", "2003-02-15")
1943B <- data.frame(b = 1:4)
1944row.names(B) <- c("2002-09-15", "2002-10-15", "2002-11-15", "2002-12-15")
1945merge(A, B, by=0, all=TRUE)
1946
1947
1948## assigning to a list loop index could alter the index (PR#9216)
1949L <- list(a = list(txt = "original value"))
1950f <- function(LL) {
1951    for (ll in LL) ll$txt <- "changed in f"
1952    LL
1953}
1954f(L)
1955L
1956## both were changed < 2.4.0
1957
1958
1959## summary.mlm misbehaved with na.action = na.exclude
1960n <- 50
1961x <- runif(n=n)
1962y1 <- 2 * x + rnorm(n=n)
1963y2 <- 5 * x + rnorm(n=n)
1964y2[sample(1:n, size=5)] <- NA
1965y <- cbind(y1, y2)
1966fit <- lm(y ~ 1, na.action="na.exclude")
1967summary(fit)
1968## failed < 2.4.0
1969
1970RNGkind("default","default")## reset to default - ease  R core
1971
1972## prettyNum lost attributes (PR#8695)
1973format(matrix(1:16, 4), big.mark = ",")
1974## was a vector < 2.4.0
1975
1976
1977## printing of complex numbers of very different magnitudes
19781e100  + 1e44i
19791e100 + pi*1i*10^(c(-100,0,1,40,100))
1980## first was silly, second not rounded correctly in 2.2.0 - 2.3.1
1981## We don't get them lining up, but that is a printf issue
1982## that only happens for very large complex nos.
1983
1984
1985### end of tests added in 2.4.0 ###
1986
1987
1988## Platform-specific behaviour in lowess reported to R-help
1989## 2006-10-12 by Frank Harrell
1990x <- c(0,7,8,14,15,120,242)
1991y <- c(122,128,130,158,110,110,92)
1992lowess(x, y, iter=0)
1993lowess(x, y)
1994## MAD of iterated residuals was zero, and result depended on the platform.
1995
1996
1997## PR#9263: problems with R_Visible
1998a <- list(b=5)
1999a[[(t<-'b')]]
2000x <- matrix(5:-6, 3)
2001x[2, invisible(3)]
2002## both invisible in 2.4.0
2003
2004
2005### end of tests added in 2.4.1 ###
2006
2007
2008## tests of deparsing
2009x <-list(a = NA, b = as.integer(NA), c=0+NA, d=0i+NA,
2010         e = 1, f = 1:1, g = 1:3, h = c(NA, 1:3),
2011         i = as.character(NA), j = c("foo", NA, "bar")
2012         )
2013dput(x, control=NULL)
2014dput(x, control="keepInteger")
2015dput(x, control="keepNA")
2016dput(x)
2017dput(x, control="all")
2018dput(x, control=c("all", "S_compatible"))
2019tmp <- tempfile(tmpdir = getwd())
2020dput(x, tmp, control="all")
2021stopifnot(identical(dget(tmp), x))
2022dput(x, tmp, control=c("all", "S_compatible"))
2023stopifnot(identical(dget(tmp), x))
2024unlink(tmp)
2025## changes in 2.5.0
2026
2027
2028## give better error message for nls with no parameters
2029## Ivo Welch, R-help, 2006-12-23.
2030d <- data.frame(y= runif(10), x=runif(10))
2031try(nls(y ~ 1/(1+x), data = d, start=list(x=0.5,y=0.5), trace=TRUE))
2032## changed in 2.4.1 patched
2033
2034
2035## cut(breaks="years"), in part PR#9433
2036cut(as.Date(c("2000-01-17","2001-01-13","2001-01-20")), breaks="years")
2037cut(as.POSIXct(c("2000-01-17","2001-01-13","2001-01-20")), breaks="years")
2038## did not get day 01 < 2.4.1 patched
2039
2040
2041## manipulating rownames: problems in pre-2.5.0
2042A <- data.frame(a=character(0))
2043try(row.names(A) <- 1:10) # succeeded in Dec 2006
2044A <- list(a=1:3)
2045class(A) <- "data.frame"
2046row.names(A) <- letters[24:26] # failed at one point in Dec 2006
2047A
2048##
2049
2050
2051## extreme cases for subsetting of data frames
2052w <- women[1, ]
2053w[]
2054w[,drop = TRUE]
2055w[1,]
2056w[,]
2057w[1, , drop = FALSE]
2058w[, , drop = FALSE]
2059w[1, , drop = TRUE]
2060w[, , drop = TRUE]
2061## regression test: code changed for 2.5.0
2062
2063
2064## data.frame() with zero columns ignored 'row.names'
2065(x <- data.frame(row.names=1:4))
2066nrow(x)
2067row.names(x)
2068attr(x, "row.names")
2069## ignored prior to 2.5.0.
2070
2071
2072## identical on data.frames
2073d0 <- d1 <- data.frame(1:4, row.names=1:4)
2074row.names(d0) <- NULL
2075dput(d0)
2076dput(d1)
2077identical(d0, d1)
2078all.equal(d0, d1)
2079row.names(d1) <- as.character(1:4)
2080dput(d1)
2081identical(d0, d1)
2082all.equal(d0, d1)
2083## identical used internal representation prior to 2.5.0
2084
2085
2086## all.equal
2087# ignored check.attributes in 2.4.1
2088all.equal(data.frame(x=1:5, row.names=letters[1:5]),
2089          data.frame(x=1:5,row.names=LETTERS[1:5]),
2090          check.attributes=FALSE)
2091# treated logicals as numeric
2092all.equal(c(T, F, F), c(T, T, F))
2093all.equal(c(T, T, F), c(T, F, F))
2094# ignored raw:
2095all.equal(as.raw(1:3), as.raw(1:3))
2096all.equal(as.raw(1:3), as.raw(3:1))
2097##
2098
2099
2100## tests of deparsing
2101# if we run this from stdin, we will have no source, so fake it
2102f <- function(x, xm  = max(1L, x)) {xx <- 0L; yy <- NA_real_}
2103attr(f, "srcref") <- srcref(srcfilecopy("",
2104    "function(x, xm  = max(1L, x)) {xx <- 0L; yy <- NA_real_}"),
2105    c(1L, 1L, 1L, 56L))
2106f # uses the source
2107dput(f) # not source
2108dput(f, control="all") # uses the source
2109cat(deparse(f), sep="\n")
2110dump("f", file="")
2111# remove the source
2112attr(f, "srcref") <- NULL
2113f
2114dput(f, control="all")
2115dump("f", file="")
2116
2117expression(bin <- bin + 1L)
2118## did not preserve e.g. 1L at some point in pre-2.5.0
2119
2120
2121## NAs in substr were handled as large negative numbers
2122x <- "abcde"
2123substr(x, 1, 3)
2124substr(x, NA, 1)
2125substr(x, 1, NA)
2126substr(x, NA, 3) <- "abc"; x
2127substr(x, 1, NA) <- "AA"; x
2128substr(x, 1, 2) <- NA_character_; x
2129## "" or no change in 2.4.1, except last
2130
2131
2132## regression tests for pmin/pmax, rewritten in C for 2.5.0
2133# NULL == integer(0)
2134pmin(NULL, integer(0))
2135pmax(integer(0), NULL)
2136pmin(NULL, 1:3)# now ok
2137pmax(pi, NULL, 2:4)
2138
2139x <- c(1, NA, NA, 4, 5)
2140y <- c(2, NA, 4, NA, 3)
2141pmin(x, y)
2142stopifnot(identical(pmin(x, y), pmin(y, x)))
2143pmin(x, y, na.rm=TRUE)
2144stopifnot(identical(pmin(x, y, na.rm=TRUE), pmin(y, x, na.rm=TRUE)))
2145pmax(x, y)
2146stopifnot(identical(pmax(x, y), pmax(y, x)))
2147pmax(x, y, na.rm=TRUE)
2148stopifnot(identical(pmax(x, y, na.rm=TRUE), pmax(y, x, na.rm=TRUE)))
2149
2150x <- as.integer(x); y <- as.integer(y)
2151pmin(x, y)
2152stopifnot(identical(pmin(x, y), pmin(y, x)))
2153pmin(x, y, na.rm=TRUE)
2154stopifnot(identical(pmin(x, y, na.rm=TRUE), pmin(y, x, na.rm=TRUE)))
2155pmax(x, y)
2156stopifnot(identical(pmax(x, y), pmax(y, x)))
2157pmax(x, y, na.rm=TRUE)
2158stopifnot(identical(pmax(x, y, na.rm=TRUE), pmax(y, x, na.rm=TRUE)))
2159
2160x <- as.character(x); y <- as.character(y)
2161pmin(x, y)
2162stopifnot(identical(pmin(x, y), pmin(y, x)))
2163pmin(x, y, na.rm=TRUE)
2164stopifnot(identical(pmin(x, y, na.rm=TRUE), pmin(y, x, na.rm=TRUE)))
2165pmax(x, y)
2166stopifnot(identical(pmax(x, y), pmax(y, x)))
2167pmax(x, y, na.rm=TRUE)
2168stopifnot(identical(pmax(x, y, na.rm=TRUE), pmax(y, x, na.rm=TRUE)))
2169
2170# tests of classed quantities
2171x <- .leap.seconds[1:23]; y <- rev(x)
2172x[2] <- y[2] <- x[3] <- y[4] <- NA
2173format(pmin(x, y), tz="GMT")  # TZ names differ by platform
2174class(pmin(x, y))
2175stopifnot(identical(pmin(x, y), pmin(y, x)))
2176format(pmin(x, y, na.rm=TRUE), tz="GMT")
2177stopifnot(identical(pmin(x, y, na.rm=TRUE), pmin(y, x, na.rm=TRUE)))
2178format(pmax(x, y), tz="GMT")
2179stopifnot(identical(pmax(x, y), pmax(y, x)))
2180format(pmax(x, y, na.rm=TRUE), tz="GMT")
2181stopifnot(identical(pmax(x, y, na.rm=TRUE), pmax(y, x, na.rm=TRUE)))
2182
2183x <- as.POSIXlt(x, tz="GMT"); y <- as.POSIXlt(y, tz="GMT")
2184format(pmin(x, y), tz="GMT")
2185class(pmin(x, y))
2186stopifnot(identical(pmin(x, y), pmin(y, x)))
2187format(pmin(x, y, na.rm=TRUE), tz="GMT")
2188stopifnot(identical(pmin(x, y, na.rm=TRUE), pmin(y, x, na.rm=TRUE)))
2189format(pmax(x, y), tz="GMT")
2190stopifnot(identical(pmax(x, y), pmax(y, x)))
2191format(pmax(x, y, na.rm=TRUE), tz="GMT")
2192stopifnot(identical(pmax(x, y, na.rm=TRUE), pmax(y, x, na.rm=TRUE)))
2193## regresion tests
2194
2195
2196## regression tests on names of 1D arrays
2197x <- as.array(1:3)
2198names(x) <- letters[x] # sets dimnames, really
2199names(x)
2200dimnames(x)
2201attributes(x)
2202names(x) <- NULL
2203attr(x, "names") <- LETTERS[x] # sets dimnames, really
2204names(x)
2205dimnames(x)
2206attributes(x)
2207## regression tests
2208
2209
2210## regression tests on NA attribute names
2211x <- 1:3
2212attr(x, "NA") <- 4
2213attributes(x)
2214attr(x, "NA")
2215attr(x, NA_character_)
2216try(attr(x, NA_character_) <- 5)
2217## prior to 2.5.0 NA was treated as "NA"
2218
2219
2220## qr with pivoting (PR#9623)
2221A <- matrix(c(0,0,0, 1,1,1), nrow = 3,
2222            dimnames = list(letters[1:3], c("zero","one")))
2223y <- matrix(c(6,7,8), nrow = 3, dimnames = list(LETTERS[1:3], "y"))
2224qr.coef(qr(A), y)
2225qr.fitted(qr(A), y)
2226
2227qr.coef(qr(matrix(0:1, 1, dimnames=list(NULL, c("zero","one")))), 5)
2228## coef names were returned unpivoted <= 2.5.0
2229
2230## readChar read extra items, terminated on zeros
2231x <- as.raw(65:74)
2232readChar(x, nchar=c(3,3,0,3,3,3))
2233f <- tempfile(tmpdir = getwd())
2234writeChar("ABCDEFGHIJ", con=f, eos=NULL)
2235readChar(f, nchar=c(3,3,0,3,3,3))
2236unlink(f)
2237##
2238
2239
2240## corner cases for cor
2241set.seed(1)
2242X <- cbind(NA, 1:3, rnorm(3))
2243try(cor(X, use = "complete"))
2244try(cor(X, use = "complete", method="spearman"))
2245try(cor(X, use = "complete", method="kendall"))
2246cor(X, use = "pair")
2247cor(X, use = "pair", method="spearman")
2248cor(X, use = "pair", method="kendall")
2249
2250X[1,1] <- 1
2251cor(X, use = "complete")
2252cor(X, use = "complete", method="spearman")
2253cor(X, use = "complete", method="kendall")
2254cor(X, use = "pair")
2255cor(X, use = "pair", method="spearman")
2256cor(X, use = "pair", method="kendall")
2257## not consistent in 2.6.x
2258
2259
2260## confint on rank-deficient models (in part, PR#10494)
2261junk <- data.frame(x = rep(1, 10L),
2262                   u = factor(sample(c("Y", "N"), 10, replace=TRUE)),
2263                   ans = rnorm(10))
2264fit <-  lm(ans ~ x + u, data = junk)
2265confint(fit)
2266confint.default(fit)
2267## Mismatch gave NA for 'u' in 2.6.1
2268
2269
2270## corrupt data frame produced by subsetting (PR#10574)
2271x <- data.frame(a=1:3, b=2:4)
2272x[,3] <- x
2273x
2274## warning during printing < 2.7.0
2275
2276
2277## format.factor used to lose dim[names] and names (PR#11512)
2278x <- factor(c("aa", letters[-1]))
2279dim(x) <- c(13,2)
2280format(x, justify="right")
2281##
2282
2283
2284## removing columns in within (PR#1131)
2285abc <- data.frame(a=1:5, b=2:6, c=3:7)
2286within(abc, b<-NULL)
2287within(abc,{d<-a+7;b<-NULL})
2288within(abc,{a<-a+7;b<-NULL})
2289## Second produced corrupt data frame in 2.7.1
2290
2291
2292## aggregate on an empty data frame (PR#13167)
2293z <- data.frame(a=integer(0), b=numeric(0))
2294try(aggregate(z, by=z[1], FUN=sum))
2295## failed in unlist in 2.8.0, now gives explicit message.
2296aggregate(data.frame(a=1:10)[F], list(rep(1:2, each=5)), sum)
2297## used to fail obscurely.
2298
2299
2300## subsetting data frames with duplicate rows
2301z <- data.frame(a=1, a=2, b=3, check.names=FALSE)
2302z[] # OK
2303z[1, ]
2304## had row names a, a.1, b in 2.8.0.
2305
2306
2307## incorrect warning due to lack of fuzz.
2308TS <-  ts(co2[1:192], freq=24)
2309tmp2 <- window(TS, start(TS), end(TS))
2310## warned in 2.8.0
2311
2312## failed to add tag
2313Call <- call("foo", 1)
2314Call[["bar"]] <- 2
2315Call
2316## unnamed call in 2.8.1
2317
2318options(keep.source = TRUE)
2319## $<- on pairlists failed to duplicate (from Felix Andrews,
2320## https://stat.ethz.ch/pipermail/r-devel/2009-January/051698.html)
2321foo <- function(given = NULL) {
2322    callObj <- quote(callFunc())
2323    if(!is.null(given)) callObj$given <- given
2324    if (is.null(given)) callObj$default <- TRUE
2325    callObj
2326}
2327
2328foo()
2329foo(given = TRUE)
2330foo("blah blah")
2331foo(given = TRUE)
2332foo()
2333## altered foo() in 2.8.1.
2334
2335## Using  '#' flag in  sprintf():
2336forms <- c("%#7.5g","%#5.f", "%#7x", "%#5d", "%#9.0e")
2337nums <- list(-3.145, -31,   0xabc,  -123L, 123456)
2338rbind(mapply(sprintf, forms,               nums),
2339      mapply(sprintf, sub("#", '', forms), nums))
2340## gave an error in pre-release versions of 2.9.0
2341
2342## (auto)printing of functions {with / without source attribute},
2343## including primitives
2344sink(con <- textConnection("of", "w")) ; c ; sink(NULL); close(con)
2345of2 <- capture.output(print(c))
2346stopifnot(identical(of2, of),
2347          identical(of2, "function (...)  .Primitive(\"c\")"))
2348## ^^ would have failed up to R 2.9.x
2349foo
2350print(foo, useSource = FALSE)
2351attr(foo, "srcref") <- NULL
2352foo
2353(f <- structure(function(){}, note = "just a note",
2354                yada = function() "not the same"))
2355print(f, useSource = TRUE)
2356print(f, useSource = FALSE) # must print attributes
2357print.function <- function(x, ...) {
2358    cat("my print(<function>): "); str(x, give.attr=FALSE); invisible(x) }
2359print.function
2360print(print.function)
2361rm(print.function)
2362## auto-printing and printing differed up to R 2.9.x -- and then *AGAIN* in R 3.6.0
2363
2364
2365## Make sure deparsing does not reset parameters
2366print(list(f, expression(foo), f, quote(foo), f, base::list, f),
2367      useSource = FALSE)
2368
2369printCoefmat(cbind(0,1))
2370## would print NaN up to R 2.9.0
2371
2372
2373## continuity correction for Kendall's tau.  Improves this example.
2374cor.test(c(1, 2, 3, 4, 5), c(8, 6, 7, 5, 3), method = "kendall",
2375         exact = TRUE)
2376cor.test(c(1, 2, 3, 4, 5), c(8, 6, 7, 5, 3), method = "kendall",
2377         exact = FALSE)
2378cor.test(c(1, 2, 3, 4, 5), c(8, 6, 7, 5, 3), method = "kendall",
2379         exact = FALSE, continuity = TRUE)
2380# and a little for Spearman's
2381cor.test(c(1, 2, 3, 4, 5), c(8, 6, 7, 5, 3), method = "spearman",
2382         exact = TRUE)
2383cor.test(c(1, 2, 3, 4, 5), c(8, 6, 7, 5, 3), method = "spearman",
2384         exact = FALSE)
2385cor.test(c(1, 2, 3, 4, 5), c(8, 6, 7, 5, 3), method = "spearman",
2386         exact = FALSE, continuity = TRUE)
2387## Kendall case is wish of PR#13691
2388
2389
2390## corrupt data frame, PR#13724
2391foo <- matrix(1:12, nrow = 3)
2392bar <- as.data.frame(foo)
2393val <- integer(0)
2394try(bar$NewCol <- val)
2395# similar, not in the report
2396try(bar[["NewCol"]] <- val)
2397# [ ] is tricker, so just check the result is reasonable and prints
2398bar["NewCol"] <- val
2399bar[, "NewCol2"] <- val
2400bar[FALSE, "NewCol3"] <- val
2401bar
2402## Succeeded but gave corrupt result in 2.9.0
2403
2404
2405## Printing NA_complex_
2406m22 <- matrix(list(NA_complex_, 3, "A string", NA_complex_), 2,2)
2407print(m22)
2408print(m22, na.print="<missing value>")
2409## used uninitialized variable in C, noticably Windows, for R <= 2.9.0
2410
2411
2412## non-standard variable names in update etc
2413## never guaranteed to work, requested by Sundar Dorai-Raj in
2414## https://stat.ethz.ch/pipermail/r-devel/2009-July/054184.html
2415update(`a: b` ~ x, ~ . + y)
2416## 2.9.1 dropped backticks
2417
2418
2419## print(ls.str(.)) did evaluate calls
2420E <- new.env(); E$cl <- call("print", "Boo !")
2421ls.str(E)
2422## 2.10.0 did print..
2423
2424
2425## complete.cases with no input
2426try(complete.cases())
2427try(complete.cases(list(), list()))
2428## gave unhelpful messages in 2.10.0, silly results in pre-2.10.1
2429
2430
2431## error messages from (C-level) evalList
2432tst <- function(y) { stopifnot(is.numeric(y)); y+ 1 }
2433try(tst()) # even nicer since R 3.5.0's change to sequential stopifnot()
2434try(c(1,,2))
2435## change in 2.8.0 made these less clear
2436
2437
2438## empty levels from cut.Date (cosmetic, PR#14162)
2439x <- as.Date(c("2009-03-21","2009-03-31"))
2440cut(x, breaks= "quarter") # had two levels in 2.10.1
2441cut(as.POSIXlt(x), breaks= "quarter")
2442## remove empty final level
2443
2444
2445## tests of error conditions in switch()
2446switch("a", a=, b=, c=, 4)
2447switch("a", a=, b=, c=, )
2448.Last.value
2449switch("a", a=, b=, c=, invisible(4))
2450.Last.value
2451## visiblilty changed in 2.11.0
2452
2453
2454## rounding error in aggregate.ts
2455## https://stat.ethz.ch/pipermail/r-devel/2010-April/057225.html
2456x <- rep(6:10, 1:5)
2457aggregate(as.ts(x), FUN = mean, ndeltat = 5)
2458x <- rep(6:10, 1:5)
2459aggregate(as.ts(x), FUN = mean, nfrequency = 0.2)
2460## platform-dependent in 2.10.1
2461
2462
2463## wish of PR#9574
2464a <- c(0.1, 0.3, 0.4, 0.5, 0.3, 0.0001)
2465format.pval(a, eps=0.01)
2466format.pval(a, eps=0.01, nsmall =2)
2467## granted in 2.12.0
2468
2469
2470## printing fractional dates
2471as.Date(0.5, origin="1969-12-31")
2472## changed to round down in 2.12.1
2473
2474
2475## printing data frames with  ""  colnames
2476dfr <- data.frame(x=1:6, CC=11:16, f = gl(3,2)); colnames(dfr)[2] <- ""
2477dfr
2478## now prints the same as data.matrix(dfr) does here
2479
2480
2481## format(., zero.print) --> prettyNum()
2482set.seed(9); m <- matrix(local({x <- rnorm(40)
2483                                sign(x)*round(exp(2*x))/10}), 8,5)
2484noquote(format(m, zero.print= "."))
2485## used to print  ". 0" instead of ".  "
2486
2487
2488## tests of NA having precedence over NaN -- all must print "NA"
2489min(c(NaN, NA))
2490min(c(NA, NaN)) # NaN in 2.12.2
2491min(NaN, NA_real_)  # NaN in 2.12.2
2492min(NA_real_, NaN)
2493max(c(NaN, NA))
2494max(c(NA, NaN))  # NaN in 2.12.2
2495max(NaN, NA_real_)  # NaN in 2.12.2
2496max(NA_real_, NaN)
2497## might depend on compiler < 2.13.0
2498
2499
2500## PR#14514
2501# Data are from Conover, "Nonparametric Statistics", 3rd Ed, p. 197,
2502# re-arranged to make a lower-tail test the issue of relevance:  we
2503# want to see if pregnant nurses exposed to nitrous oxide have higher
2504# rates of miscarriage, stratifying on the type of nurse.
2505Nitrous <- array(c(32,210,8,26,18,21,3,3,7,75,0,10), dim = c(2,2,3),
2506                 dimnames = list(c("Exposed","NotExposed"),
2507                 c("FullTerm","Miscarriage"),
2508                 c("DentalAsst","OperRoomNurse","OutpatientNurse")))
2509mantelhaen.test(Nitrous, exact=TRUE, alternative="less")
2510mantelhaen.test(Nitrous, exact=FALSE, alternative="less")
2511## exact = FALSE gave the wrong tail in 2.12.2.
2512
2513
2514## scan(strip.white=TRUE) could strip trailing (but not leading) space
2515## inside quoted strings.
2516writeLines(' "  A  "; "B" ;"C";" D ";"E ";  F  ;G  ', "foo")
2517cat(readLines("foo"), sep = "\n")
2518scan('foo', list(""), sep=";")[[1]]
2519scan('foo', "", sep=";")
2520scan('foo', list(""), sep=";", strip.white = TRUE)[[1]]
2521scan('foo', "", sep=";", strip.white = TRUE)
2522unlink('foo')
2523
2524writeLines(' "  A  "\n "B" \n"C"\n" D "\n"E "\n  F  \nG  ', "foo2")
2525scan('foo2', "")
2526scan('foo2', "", strip.white=TRUE) # documented to be ignored ...
2527unlink('foo2')
2528## Changed for 2.13.0, found when investigating non-bug PR#14522.
2529
2530
2531## PR#14488: missing values in rank correlations
2532set.seed(1)
2533x <- runif(10)
2534y <- runif(10)
2535x[3] <- NA; y[5] <- NA
2536xy <- cbind(x, y)
2537
2538cor(x, y, method = "spearman", use = "complete.obs")
2539cor(x, y, method = "spearman", use = "pairwise.complete.obs")
2540cor(na.omit(xy),  method = "spearman", use = "complete.obs")
2541cor(xy,  method = "spearman", use = "complete.obs")
2542cor(xy,  method = "spearman", use = "pairwise.complete.obs")
2543## inconsistent in R < 2.13.0
2544
2545
2546## integer overflow in rowsum() went undetected
2547# https://stat.ethz.ch/pipermail/r-devel/2011-March/060304.html
2548x <- 2e9L
2549rowsum(c(x, x), c("a", "a"))
2550rowsum(data.frame(z = c(x, x)), c("a", "a"))
2551## overflow in R < 2.13.0.
2552
2553
2554## method dispatch in [[.data.frame:
2555## https://stat.ethz.ch/pipermail/r-devel/2011-April/060409.html
2556d <- data.frame(num = 1:4,
2557          fac = factor(letters[11:14], levels = letters[1:15]),
2558          date = as.Date("2011-04-01") + (0:3),
2559          pv = package_version(c("1.2-3", "4.5", "6.7", "8.9-10")))
2560for (i in seq_along(d)) print(d[[1, i]])
2561## did not dispatch in R < 2.14.0
2562
2563
2564## some tests of 24:00 as midnight
2565as.POSIXlt("2011-05-16 24:00:00", tz = "GMT")
2566as.POSIXlt("2010-01-31 24:00:00", tz = "GMT")
2567as.POSIXlt("2011-02-28 24:00:00", tz = "GMT")
2568as.POSIXlt("2008-02-28 24:00:00", tz = "GMT")
2569as.POSIXlt("2008-02-29 24:00:00", tz = "GMT")
2570as.POSIXlt("2010-12-31 24:00:00", tz = "GMT")
2571## new in 2.14.0
2572
2573
2574## Unwarranted conversion of logical values
2575try(double(FALSE))
2576x <- 1:3
2577try(length(x) <- TRUE)
2578## coerced to integer in 2.13.x
2579
2580
2581## filter(recursive = TRUE) on input with NAs
2582# https://stat.ethz.ch/pipermail/r-devel/2011-July/061547.html
2583x <- c(1:4, NA, 6:9)
2584cbind(x, "1"=filter(x, 0.5, method="recursive"),
2585         "2"=filter(x, c(0.5, 0.0), method="recursive"),
2586         "3"=filter(x, c(0.5, 0.0, 0.0), method="recursive"))
2587## NAs in wrong place in R <= 2.13.1.
2588
2589
2590## PR#14679.  Format depends if TZ is set.
2591x <- as.POSIXlt(c("2010-02-27 22:30:33", "2009-08-09 06:01:03",
2592                  "2010-07-23 17:29:59"))
2593stopifnot(!is.na(trunc(x, units = "days")[1:3]))
2594## gave NAs after the first in R < 2.13.2
2595
2596
2597## explicit error message for silly input (tol = 0)
2598aa <- c(1, 2, 3, 8, 8, 8, 8, 8, 8, 8, 8, 8, 12, 13, 14)
2599try(smooth.spline(aa, seq_along(aa)))
2600fit <- smooth.spline(aa, seq_along(aa), tol = 0.1)
2601# actual output is too unstable to diff.
2602## Better message from R 2.14.2
2603
2604
2605## PR#14840
2606d <- data.frame(x = 1:9,
2607                y = 1:9 + 0.1*c(1, 2, -1, 0, 1, 1000, 0, 1, -1),
2608                w = c(1, 0.5, 2, 1, 2, 0, 1, 2, 1))
2609fit <- lm(y ~ x, data=d, weights=w)
2610summary(fit)
2611## issue is how the 5-number summary is labelled
2612## (also seen in example(case.names))
2613
2614
2615## is.unsorted got it backwards for dataframes of more than one column
2616## it is supposed to look for violations of x[2] > x[1], x[3] > x[2], etc.
2617is.unsorted(data.frame(x=2:1))
2618is.unsorted(data.frame(x=1:2, y=3:4))
2619is.unsorted(data.frame(x=3:4, y=1:2))
2620## R < 2.15.1 got these as FALSE, TRUE, FALSE.
2621
2622
2623library("methods")# (not needed here)
2624assertError <- tools::assertError
2625assertErrorV <- function(expr) assertError(expr, verbose=TRUE)
2626assertErrorV( getMethod(ls, "bar", fdef=ls) )
2627assertErrorV( getMethod(show, "bar") )
2628## R < 2.15.1 gave
2629##   cannot coerce type 'closure' to vector of type 'character'
2630
2631
2632## corner cases for array
2633# allowed, gave non-array in 2.15.x
2634try(array(1, integer()))
2635# if no dims, an error to supply dimnames
2636try(array(1, integer(), list(1, 2)))
2637##
2638
2639
2640## is.na() on an empty dataframe (PR#14059)
2641DF <- data.frame(row.names=1:3)
2642is.na(DF); str(.Last.value)
2643is.na(DF[FALSE, ]); str(.Last.value)
2644## first failed in R 2.15.1, second gave NULL
2645
2646
2647## split() with dots in levels
2648df <- data.frame(x = rep(c("a", "a.b"), 3L), y = rep(c("b.c", "c"), 3L),
2649                 z = 1:6)
2650df
2651split(df, df[, 1:2]) # default is sep = "."
2652split(df, df[, 1:2], sep = ":")
2653##
2654
2655
2656## The difference between sort.list and order
2657z <- c(4L, NA, 2L, 3L, NA, 1L)
2658order(z, na.last = NA)
2659sort.list(z, na.last = NA)
2660sort.list(z, na.last = NA, method = "shell")
2661sort.list(z, na.last = NA, method = "quick")
2662sort.list(z, na.last = NA, method = "radix")
2663## Differences first documented in R 2.15.2
2664
2665
2666## PR#15028: names longer than cutoff NB (= 1000)
2667NB <- 1000
2668lns <- capture.output(
2669    setNames(c(255, 1000, 30000),
2670             c(paste(rep.int("a", NB+2), collapse=""),
2671               paste(rep.int("b", NB+2), collapse=""),
2672               paste(rep.int("c", NB+2), collapse=""))))
2673sub("^ +", '', lns[2* 1:3])
2674## *values* were cutoff when printed
2675
2676
2677## allows deparse limits to be set
2678form <- reallylongnamey ~ reallylongnamex0 + reallylongnamex1 + reallylongnamex2 + reallylongnamex3
2679form
2680op <- options(deparse.cutoff=80)
2681form
2682options(deparse.cutoff=50)
2683form
2684options(op)
2685## fixed to 60 in R 2.15.x
2686
2687
2688## PR#15179: user defined binary ops were not deparsed properly
2689quote( `%^%`(x, `%^%`(y,z)) )
2690quote( `%^%`(x) )
2691##
2692
2693
2694## Anonymous function calls were not deparsed properly
2695substitute(f(x), list(f = function(x) x + 1))
2696substitute(f(x), list(f = quote(function(x) x + 1)))
2697substitute(f(x), list(f = quote(f+g)))
2698substitute(f(x), list(f = quote(base::mean)))
2699substitute(f(x), list(f = quote(a[n])))
2700substitute(f(x), list(f = quote(g(y))))
2701## The first three need parens, the last three don't.
2702
2703
2704## PR#15247 : str() on invalid data frame names (where print() works):
2705d <- data.frame(1:3, "B", 4, stringsAsFactors=TRUE)
2706names(d) <- c("A", "B\xba","C\xabcd")
2707str(d)
2708## gave an error in R <= 3.0.0
2709
2710
2711## PR#15299 : adding a simple vector to a classed object produced a bad result:
27121:2 + table(1:2)
2713## Printed the class attribute in R <= 3.0.0
2714
2715
2716## PR#15311 : regmatches<- mishandled regexpr results.
2717  x <- c('1', 'B', '3')
2718  m <- regexpr('\\d', x)
2719  regmatches(x, m) <- c('A', 'C')
2720  print(x)
2721## Gave a warning and a wrong result up to 3.0.1
2722
2723
2724## Bad warning found by Radford Neal
2725  saveopt <- options(warnPartialMatchDollar=TRUE)
2726  pl <- pairlist(abc=1, def=2)
2727  pl$ab
2728  if (!is.null(saveopt[["warnPartialMatchDollar"]])) options(saveopt)
2729## 'abc' was just ''
2730
2731
2732## seq() with NaN etc inputs now gives explicit error messages
2733try(seq(NaN))
2734try(seq(to = NaN))
2735try(seq(NaN, NaN))
2736try(seq.int(NaN))
2737try(seq.int(to = NaN))
2738try(seq.int(NaN, NaN))
2739## R 3.0.1 gave messages from ':' or about negative-length vectors.
2740
2741
2742## Some dimnames were lost from 1D arrays: PR#15301
2743x <- array(0:2, dim=3, dimnames=list(d1=LETTERS[1:3]))
2744x
2745x[]
2746x[3:1]
2747x <- array(0, dimnames=list(d1="A"))
2748x
2749x[]
2750x[drop = FALSE]
2751## lost dimnames in 3.0.1
2752
2753
2754## PR#15396
2755load(file.path(Sys.getenv('SRCDIR'), 'arima.rda'))
2756(f1 <- arima(x, xreg = xreg, order = c(1,1,1), seasonal = c(1,0,1)))
2757(f2 <- arima(diff(x), xreg = diff(xreg), order = c(1,0,1), seasonal = c(1,0,1),
2758             include.mean = FALSE))
2759stopifnot(all.equal(coef(f1), coef(f2), tolerance = 1e-3, check.names = FALSE))
2760## first gave local optim in 3.0.1
2761
2762## all.equal always checked the names
2763x <- c(a=1, b=2)
2764y <- c(a=1, d=2)
2765all.equal(x, y, check.names = FALSE)
2766## failed on mismatched attributes
2767
2768
2769## PR#15411, plus digits change
2770format(9992, digits = 3)
2771format(9996, digits = 3)
2772format(0.0002, digits = 0, nsmall = 2)
2773format(pi*10, digits = 0, nsmall = 1)
2774## second added an extra space; 3rd and 4th were not allowed.
2775
2776## and one branch of this was wrong:
2777xx <- c(-86870268, 107833358, 302536985, 481015309, 675718935, 854197259,
2778        1016450281, 1178703303, 1324731023, 1454533441)
2779xx
2780## dropped spaces without long doubles
2781
2782## and rounding was being detected improperly (PR#15583)
27831000* ((10^(1/4)) ^ c(0:4))
27847/0.07
2785## Spacing was incorrect
2786
2787
2788## PR#15468
2789M <- matrix(11:14, ncol=2, dimnames=list(paste0("Row", 1:2), paste0("Col",
27901:2)))
2791L <- list(elem1=1, elem2=2)
2792rbind(M, L)
2793rbind(L, M)
2794cbind(M, L)
2795cbind(L, M)
2796## lost the dim of M, so returned NULL entries
2797
2798
2799## NA_character_ was not handled properly in min and max (reported by Magnus Thor Torfason)
2800str(min(NA, "bla"))
2801str(min("bla", NA))
2802str(min(NA_character_, "bla"))
2803str(max(NA, "bla"))
2804str(max("bla", NA))
2805str(max(NA_character_, "bla"))
2806## NA_character_ could be treated as "NA"; depending on the locale, it would not necessarily
2807## be the min or max.
2808
2809
2810## When two entries needed to be cut to width, str() mixed up
2811## the values (reported by Gerrit Eichner)
2812oldopts <- options(width=70)
2813n <- 11      # number of rows of data frame
2814M <- 10000   # order of magnitude of numerical values
2815longer.char.string <- "zjtvorkmoydsepnxkabmeondrjaanutjmfxlgzmrbjp"
2816X <- data.frame( A = 1:n * M,
2817                 B = factor(rep(longer.char.string, n)))
2818str( X, strict.width = "cut")
2819options(oldopts)
2820## The first row of the str() result was duplicated.
2821
2822
2823## PR15624: rounding in extreme cases
2824dpois(2^52,1,1)
2825dpois(2^52+1,1,1)
2826## second warned in R 3.0.2.
2827
2828
2829## Example from PR15625
2830f <- file.path(Sys.getenv('SRCDIR'), 'EmbeddedNuls.csv')
2831## This is a file with a UTF-8 BOM and some fields which are a single nul.
2832## The output does rely on this being run in a non-UTF-8 locale (C in tests).
2833read.csv(f) # warns
2834read.csv(f, skipNul = TRUE, fileEncoding = "UTF-8-BOM")
2835## 'skipNul' is new in 3.1.0.  Should not warn on BOM, ignore in second.
2836
2837
2838## all.equal datetime method
2839x <- Sys.time()
2840all.equal(x,x)
2841
2842# FIXME: check.tzone = FALSE needed because since 79037, all.equal.POSIXt
2843# strictly reports "" and the current time zone (even from TZ environment
2844# variable) as different.  The conversion round-trip from Sys.time()
2845# (POSIXct) via POSIXlt and back to POSIXct creates an object with the
2846# current time zone, yet the original is with "" as time zone (and both
2847# refer to the same time zone).
2848all.equal(x, as.POSIXlt(x), check.tzone = FALSE)
2849
2850all.equal(x, as.numeric(x))  # errored in R <= 4.0.2
2851all.equal(x, as.POSIXlt(x, tz = "EST5EDT"))
2852all.equal(x, x+1e-4)
2853isTRUE(all.equal(x, x+0.002)) # message will depend on representation error
2854## as.POSIXt method is new in 3.1.0.
2855
2856
2857
2858## Misuse of PR#15633
2859try(bartlett.test(yield ~ block*N, data = npk))
2860try(fligner.test (yield ~ block*N, data = npk))
2861## used the first factor with an incorrect description in R < 3.0.3
2862
2863
2864## Misguided expectation of PR#15687
2865xx <- window(AirPassengers, start = 1960)
2866cbind(xx, xx)
2867op <- options(digits = 2)
2868cbind(xx, xx)
2869options(op)
2870## 'digits' was applied to the time.
2871
2872
2873## Related to PR#15190
2874difftime(
2875    as.POSIXct(c("1970-01-01 00:00:00", "1970-01-01 12:00:00"), tz="EST5EDT"),
2876    as.POSIXct(c("1970-01-01 00:00:00", "1970-01-01 00:00:00"), tz="UTC"))
2877## kept tzone from first arg.
2878
2879
2880## PR#15706
2881x1 <- as.dendrogram(hclust(dist(c(i=1,ii=2,iii=3,v=5,vi=6,vii=7))))
2882attr(cophenetic(x1), "Labels")
2883## gave a matrix in 3.0.3
2884
2885
2886## PR#15708
2887aa <- anova( lm(sr ~ ., data = LifeCycleSavings) )
2888op <- options(width = 50)
2889aa
2890options(width = 40)
2891aa ; options(op)
2892## did not line wrap "Signif. codes" previously
2893
2894
2895## PR#15718
2896d <- data.frame(a=1)
2897d[integer(), "a"] <- 2
2898## warned in 3.0.3.
2899
2900
2901## PR#15781
2902options(foo = 1)
2903print(options(foo = NULL))
2904## printed wrong value in 3.1.0
2905
2906
2907## getParseData bug reported by Andrew Redd
2908raw <- "
2909function( a   # parameter 1
2910         , b=2 # parameter 2
2911         ){a+b}"
2912p <- parse(text = raw)
2913getParseData(p)
2914## Got some parents wrong
2915
2916
2917## wish of PR#15819
2918set.seed(123); x <- runif(10); y <- rnorm(10)
2919op <- options(OutDec = ",")
2920fit <- lm(y ~ x)
2921summary(fit)
2922options(op)
2923## those parts using formatC still used a decimal point.
2924
2925
2926## Printing a list with "bad" component names
2927L <- list(`a\\b` = 1, `a\\c` = 2, `a\bc` = "backspace")
2928setClass("foo", representation(`\\C` = "numeric"))
2929## the next three all print correctly:
2930names(L)
2931unlist(L)
2932as.pairlist(L)
2933cat(names(L), "\n")# yes, backspace is backspace here
2934L
2935new("foo")
2936## the last two lines printed wrongly in R <= 3.1.1
2937
2938
2939## Printing of arrays where last dim(.) == 0 :
2940r <- matrix(,0,4, dimnames=list(Row=NULL, Col=paste0("c",1:4)))
2941r
2942t(r) # did not print "Row", "Col"
2943A <- array(dim=3:0, dimnames=list(D1=c("a","b","c"), D2=c("X","Y"), D3="I", D4=NULL))
2944A ## did not print *anything*
2945A[,,"I",] # ditto
2946A[,,0,]   # ditto
2947aperm(A, c(3:1,4))   # ditto
2948aperm(A, c(1:2, 4:3))# ditto
2949unname(A)            # ditto
2950format(A[,,1,])	     # ditto
2951aperm(A, 4:1) # was ok, is unchanged
2952## sometimes not printing anything in R <= 3.1.1
2953
2954
2955## Printing objects with very long names cut off literal values (PR#15999)
2956make_long_name <- function(n)
2957{
2958  paste0(rep("a", n), collapse = "")
2959}
2960setNames(TRUE, make_long_name(1000))  # value printed as TRU
2961setNames(TRUE, make_long_name(1002))  # value printed as T
2962setNames(TRUE, make_long_name(1003))  # value not printed
2963##
2964
2965
2966## PR#16437
2967dd <- data.frame(F = factor(rep(c("A","B","C"), each = 3)), num = 1:9)
2968cs <- list(F = contr.sum(3, contrasts = FALSE))
2969a1 <- aov(num ~ F, data = dd, contrasts = cs)
2970model.tables(a1, "means")
2971t1 <- TukeyHSD(a1) ## don't print to avoid precision issues.
2972a2 <- aov(num ~ 0+F, data = dd, contrasts = cs)
2973model.tables(a2, "means")
2974t2 <- TukeyHSD(a2)
2975attr(t1, "orig.call") <- attr(t2, "orig.call")
2976stopifnot(all.equal(t1, t2))
2977## functions both failed on a2 in R <= 3.2.2.
2978
2979
2980## deparse() did not add parens before [
2981substitute(a[1], list(a = quote(x * y)))
2982## should be (x * y)[1], was x * y[1]
2983# Check all levels of precedence
2984# (Comment out illegal ones)
2985quote(`$`(a :: b, c))
2986# quote(`::`(a $ b, c $ d))
2987quote(`[`(a $ b, c $ d))
2988quote(`$`(a[b], c))
2989quote(`^`(a[b], c[d]))
2990quote(`[`(a ^ b, c ^ d))
2991quote(`-`(a ^ b))
2992quote(`^`(-b, -d))
2993quote(`:`(-b, -d))
2994quote(`-`(a : b))
2995quote(`%in%`(a : b, c : d))
2996quote(`:`(a %in% b, c %in% d))
2997quote(`*`(a %in% b, c %in% d))
2998quote(`%in%`(a * b, c * d))
2999quote(`+`(a * b, c * d))
3000quote(`*`(a + b, c + d))
3001quote(`<`(a + b, c + d))
3002quote(`+`(a < b, c < d))
3003quote(`!`(a < b))
3004quote(`<`(!b, !d))
3005quote(`&`(!b, !d))
3006quote(`!`(a & b))
3007quote(`|`(a & b, c & d))
3008quote(`&`(a | b, c | d))
3009quote(`~`(a | b, c | d))
3010quote(`|`(a ~ b, c ~ d))
3011quote(`->`(a ~ b, d))
3012quote(`~`(a -> b, c -> d))
3013quote(`<-`(a, c -> d))
3014quote(`->`(a <- b, c))
3015quote(`=`(a, c <- d))
3016quote(`<-`(a, `=`(c, d)))
3017quote(`?`(`=`(a, b), `=`(c, d)))
3018quote(`=`(a, c ? d))
3019quote(`?`(a = b))
3020quote(`=`(b, ?d))
3021
3022## dput() quoted the empty symbol (PR#16686)
3023a <- alist(one = 1, two = )
3024dput(a)
3025## deparsed two to quote()
3026
3027## Deparsing of repeated unary operators; the first 3 were "always" ok:
3028quote(~~x)
3029quote(++x)
3030quote(--x)
3031quote(!!x) # was `!(!x)`
3032quote(??x) # Suboptimal
3033quote(~+-!?x) # ditto: ....`?`(x)
3034## `!` no longer produces parentheses now
3035
3036
3037## summary.data.frame() with NAs in columns of class "Date" -- PR#16709
3038x <- c(18000000, 18810924, 19091227, 19027233, 19310526, 19691228, NA)
3039x.Date <- as.Date(as.character(x), format = "%Y%m%d")
3040summary(x.Date)
3041DF.Dates <- data.frame(c1 = x.Date)
3042summary(DF.Dates) ## NA's missing from output :
3043DF.Dates$x1 <- 1:7
3044summary(DF.Dates) ## NA's still missing
3045DF.Dates$x2 <- c(1:6, NA)
3046## now, NA's show fine:
3047summary(DF.Dates)
3048## 2 of 4  summary(.) above did not show NA's  in R <= 3.2.3
3049
3050
3051## Printing complex matrix
3052matrix(1i,2,13)
3053## Spacing was wrong in R <= 3.2.4
3054
3055
3056E <- expression(poly = x^3 - 3 * x^2)
3057str(E)
3058## no longer shows "structure(...., .Names = ..)"
3059
3060
3061## summary(<logical>) working via table():
3062logi <- c(NA, logical(3), NA, !logical(2), NA)
3063summary(logi)
3064summary(logi[!is.na(logi)])
3065summary(TRUE)
3066## was always showing counts for NA's even when 0 in  2.8.0 <= R <= 3.3.1
3067ii <- as.integer(logi)
3068summary(ii)
3069summary(ii[!is.na(ii)])
3070summary(1L)
3071
3072
3073## str.default() for "AsIs" arrays
3074str(I(m <- matrix(pi*1:4, 2)))
3075## did look ugly (because of toString() for numbers) in R <= 3.3.1
3076
3077
3078## check automatic coercions from double to integer
3079##
3080## these should work due to coercion
3081sprintf("%d", 1)
3082sprintf("%d", NA_real_)
3083sprintf("%d", c(1,2))
3084sprintf("%d", c(1,NA))
3085sprintf("%d", c(NA,1))
3086##
3087## these should fail
3088assertErrorV( sprintf("%d", 1.1) )
3089assertErrorV( sprintf("%d", c(1.1,1)) )
3090assertErrorV( sprintf("%d", c(1,1.1)) )
3091assertErrorV( sprintf("%d", NaN) )
3092assertErrorV( sprintf("%d", c(1,NaN)) )
3093
3094
3095## formatting of named raws:
3096setNames(as.raw(1:3), c("a", "bbbb", "c"))
3097## was quite ugly for R <= 3.4.2
3098
3099
3100## str(x) when is.vector(x) is false :
3101str(structure(c(a = 1, b = 2:7), color = "blue"))
3102## did print " atomic [1:7] ..." in R <= 3.4.x
3103
3104
3105## check stopifnot(exprs = ....)
3106tryCatch(stopifnot(exprs = {
3107  all.equal(pi, 3.1415927)
3108  2 < 2
3109  cat("Kilroy was here!\n")
3110  all(1:10 < 12)
3111  "a" < "b"
3112}), error = function(e) e$message) -> M ; cat("Error: ", M, "\n")
3113
3114tryCatch(stopifnot(exprs = {
3115  all.equal(pi, 3.1415927)
3116  { cat("Kilroy was here!\n"); TRUE }
3117  pi < 3
3118  cat("whereas I won't be printed ...\n")
3119  all(1:10 < 12)
3120  "a" < "b"
3121}), error = function(e) e$message) -> M2 ; cat("Error: ", M2, "\n")
3122
3123stopifnot(exprs = {
3124  all.equal(pi, 3.1415927)
3125  { cat("\nKilroy was here! ... "); TRUE }
3126  pi > 3
3127  all(1:10 < 12)
3128  "a" < "b"
3129  { cat("and I'm printed as well ...\n"); TRUE}
3130})
3131## without "{ .. }" :
3132stopifnot(exprs = 2 == 2)
3133try(stopifnot(exprs = 1 > 2))
3134## passing an expression object:
3135stopifnot(exprObject = expression(2 == 2, pi < 4))
3136tryCatch(stopifnot(exprObject = expression(
3137                       2 == 2,
3138                       { cat("\n Kilroy again .."); TRUE },
3139                       pi < 4,
3140                       0 == 1,
3141                       { cat("\n no way..\n"); TRUE })),
3142         error = function(e) e$message) -> M3
3143cat("Error: ", M3, "\n")
3144## was partly not ok for many weeks in R-devel, early 2018
3145
3146
3147## print.htest() with small 'digits'
3148print(t.test(1:28), digits = 3)
3149## showed 'df = 30' from signif(*, digits=1) and too many digits for CI, in R <= 3.5.1
3150
3151
3152## str(<d.frame w/ attrib>):
3153treeA <- trees
3154attr(treeA, "someA") <- 1:77
3155str(treeA)
3156## now shows the *length* of "someA"
3157
3158
3159## summaryRprof() bug PR#15886  + "Rprof() not enabled" PR#17836
3160if(capabilities("Rprof")) {
3161    Rprof(tf <- tempfile("Rprof.out", tmpdir = getwd()), memory.profiling=TRUE, line.profiling=FALSE)
3162    out <- lapply(1:10000, rnorm, n= 512)
3163    Rprof(NULL)
3164    if(interactive())
3165        print(length(readLines(tf))) # ca. 10 .. 20 lines
3166    op <- options(warn = 2) # no warnings, even !
3167    for (cs in 1:21) s <- summaryRprof(tf, memory="tseries", chunksize=cs)
3168    ## "always" triggered an error (or a warning) in R <= 3.6.3
3169    options(op)
3170    unlink(tf)
3171}
3172
3173
3174## printing *named* complex vectors (*not* arrays), PR#17868 (and PR#18019):
3175a <- 1:12; (z <- a + a*1i); names(z) <- letters[seq_along(z)]; z
3176## fixed in R-devel in July 2020;  R 4.0.3 patched on Dec 26, 2020
3177
3178
3179## identical(*) on "..." object
3180(ddd <- (function(...) environment())(1)$...) # <...>
3181 dd2 <- (function(...) environment())(1)$...
3182stopifnot( identical(ddd, dd2) )
3183## In R <= 4.0.3,  printed to console (no warning, no message!):
3184## "Unknown Type: ... (11)"
3185
3186
3187## printCoefmat() should keep NaN values (PR#17336)
3188##cm <- summary(lm(c(0,0,0) ~ 1))$coefficients
3189cm <- cbind(Estimate = 0, SE = 0, t = NaN, "Pr(>|t|)" = NaN)
3190printCoefmat(cm)  # NaN's were replaced by NA in R < 4.1.0
3191