1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
|
#' @export
print.sir <- function(x, subset = NULL, ...) {
at <- attributes(x)$sir.meta
PF <- parent.frame(1L)
subset <- evalLogicalSubset(x, substitute(subset), enclos = PF)
x <- x[subset, ]
setDT(x)
t1 <- paste0("SIR (adjusted by ", paste(at$adjust, collapse = ', '),')',
' with ', at$conf.level*100, '% ', 'confidence intervals (', at$conf.type,')')
# cat
t3 <- paste0(' Total sir: ', round(at$pooled.sir$sir,2),' (',
round(at$pooled.sir$sir.lo,2),'-', round(at$pooled.sir$sir.hi, 2),')\n',
' Total observed: ', at$pooled.sir$observed, '\n',
' Total expected: ', round(at$pooled.sir$expected,2), '\n',
' Total person-years: ', round(at$pooled.sir$pyrs))
rv <- intersect(names(x), c('sir','sir.lo','sir.hi','observed','expected','pyrs'))
if (length(rv)) {
x[, (rv) := lapply(.SD, round, digits = 2L), .SDcols = rv]
}
rv <- intersect(names(x), c('p_value'))
if (length(rv)) {
x[, (rv) := lapply(.SD, round, digits = 4), .SDcols = rv]
}
if(is.null(at$lrt.test)) {
d <- paste("Could not test", at$lrt.test.type)
} else {
if(at$lrt.test.type == 'homogeneity') {
d <- paste("Test for homogeneity: p", p.round( c(at$lrt.test)))
}
if(at$lrt.test.type == 'trend') {
d <- paste("Test for trend: p", p.round( c(at$lrt.test)))
}
}
#b <- round(c(ta$total$sir, ta$total$sir.lo, ta$total$sir.hi), 2)
# cat('\n',"Total observed", ta$total$observed, '\n',
# "Total expected:", ta$total$expected, '\n',
# "SIR:", paste0(b[1], ' (',b[2], '-',b[3],')'), '\n',
# "Person-years:", ta$total$pyrs, '\n',
# fill=TRUE)
cat(t1, '\n')
if(x[,.N] > 1) {
cat(d, '\n')
}
cat(fill=TRUE)
cat(t3, '\n', fill=TRUE)
print(data.table(x), ...)
return(invisible())
}
#' @export
`[.sir` <- function(x, ...) {
y <- NextMethod()
if (is.data.frame(y)) {
setattr(y, "class", class(x))
setattr(y, "sir.meta", attr(x, "sir.meta"))
}
y
}
#' @import grDevices
#' @export
print.sirspline <- function(x, ...) {
if ( x$spline.dependent ) {
if( any( !is.na(x$p.values))) {
cat( 'global p-value:', p.round(x$p.values[1]),'\n' )
cat( 'level p-value:', p.round(x$p.values[2]) , fill= TRUE)
} else {
cat( 'No models compared.', fill= TRUE)
}
cat('---', '\n')
cat('Colour codes:', '\n', fill=TRUE)
} else {
for(i in 1:length(x$p.values)) {
cat( x$spline[i] ,': p ', p.round( x$p.values[[i]] ), '\n', sep = '')
}
cat(fill=TRUE)
}
# Print colour codes:
cols <- unique(x$spline.est.A[,1])
col.length <- length(cols)
print( data.frame(levels = cols, colour = palette()[1:col.length]), include.rownames = FALSE)
# Print p-values
return(invisible())
}
#' Plot method for sir-object
#'
#' Plot SIR estimates with error bars
#'
#' @seealso `[sir]`, `[sirspline]`
#'
#' @import graphics
#'
#' @author Matti Rantanen
#'
#' @param x an object returned by function `sir`
#' @param conf.int default TRUE draws confidence intervals
#' @param xlab overwrites default x-axis label
#' @param ylab overwrites default y-axis label
#' @param xlim x-axis minimum and maximum values
#' @param main optional plot title
#' @param abline logical; draws a grey line in SIR = 1
#' @param log logical; SIR is not in log scale by default
#' @param eps error bar vertical bar height (works only in 'model' or 'univariate')
#' @param left.margin adjust left marginal of the plot to fit long variable names
#' @param ... arguments passed on to plot(), segment and lines()
#'
#'
#' @details Plot SIR estimates and confidence intervals
#' \itemize{
#' \item univariate - plots SIR with univariate confidence intervals
#' \item model - plots SIR with Poisson modelled confidence intervals
#' }
#'
#' **Customize**
#' Normal plot parameters can be passed to `plot`. These can be a vector when plotting error bars:
#' \itemize{
#' \item `pch` - point type
#' \item `lty` - line type
#' \item `col` - line/point colour
#' \item `lwd` - point/line size
#' }
#'
#' **Tips for plotting splines**
#' It's possible to use `plot` to first draw the
#' confidence intervals using specific line type or colour and then plotting
#' again the estimate using `lines(... , conf.int = FALSE)` with different
#' settings. This works only when `plot.type` is 'splines'.
#'
#'
#' @examples
#' \donttest{
#' # Plot SIR estimates
#'# plot(sir.by.gender, col = c(4,2), log=FALSE, eps=0.2, lty=1, lwd=2, pch=19,
#'# main = 'SIR by gender', abline=TRUE)
#' }
#' @return
#' Always returns `NULL` invisibly.
#' This function is called for its side effects.
#' @export
plot.sir <- function(x, conf.int = TRUE, ylab, xlab, xlim, main,
eps=0.2, abline = TRUE, log = FALSE, left.margin, ...) {
a <- data.table(x)
at <- attributes(x)$sir.meta
level_names <- at$print
if(is.null(level_names)) {
levels <- 'Crude'
level_names <- levels
}
else {
q <- paste0('paste(', paste(level_names, collapse=', '),', sep = ":")' )
q <- parse(text = q)
levels <- a[, eval(q)]
}
# predefined parameters
if( missing(main) ){
main <- NA
}
if( missing(xlab) ){
xlab <- 'SIR'
}
if( missing(ylab) ){
ylab <- NA
}
if( missing(xlim) ) {
xlimit <- c(min(a$sir.lo[a$sir.lo <Inf]), max(a$sir.hi[a$sir.hi <Inf]))
xlimit <- xlimit + diff(xlimit)*c(-.3,.3)
}
else {
xlimit <- xlim
}
# par options
old_mar <- par("mar")
on.exit(par(mar = old_mar))
new.margin <- old_mar
if(missing(left.margin)) {
new.margin[2] <- 4.1 + sqrt( max(nchar(as.character(level_names))) )*2
}
else {
new.margin[2] <- left.margin
}
par(mar = new.margin)
# plot frame, estimates and CI (optional abline)
logarithm <- ''
if(log){
logarithm <- 'x'
if(xlimit[1]==0) xlimit[1] <- xlimit[1] + 0.01
}
y.axis.levels <- 1:length(levels)
plot(c(xlimit), c(min(y.axis.levels)-0.5, max(y.axis.levels)+0.5),
type='n', yaxt = 'n', xlab=xlab, ylab=ylab, log=logarithm, main = main, ...)
axis(side = 2, at = y.axis.levels, labels = levels, las=1)
if(abline) {
abline(v=1, col = 'darkgray')
}
points(a$sir, factor(y.axis.levels, labels=levels), ...)
if(conf.int) {
segments(a$sir.lo, y.axis.levels , a$sir.hi, y.axis.levels, ...)
segments(a$sir.lo, y.axis.levels - eps, a$sir.lo, y.axis.levels +eps, ... )
segments(a$sir.hi, y.axis.levels - eps, a$sir.hi, y.axis.levels +eps, ... )
}
return(invisible(NULL))
}
#' @title `plot` method for sirspline-object
#'
#' @description Plot SIR splines using R base graphics.
#'
#'
#' @import graphics
#'
#' @author Matti Rantanen
#'
#' @param x an object returned by function sirspline
#' @param conf.int logical; default TRUE draws also the 95 confidence intervals
#' @param xlab overwrites default x-axis label; can be a vector if multiple splines fitted
#' @param ylab overwrites default y-axis label; can be a vector if multiple splines fitted
#' @param log logical; default FALSE. Should the y-axis be in log scale
#' @param abline logical; draws a reference line where SIR = 1
#' @param type select `type = 'n'` to plot only figure frames
#' @param ... arguments passed on to plot()
#'
#' @details
#' In `plot.sirspline` almost every graphical parameter are user
#' adjustable, such as `ylim`, `xlim`.
#' `plot.sirsplines` calls `lines.splines` to add lines.
#'
#' The plot axis without lines can be plotted using option `type = 'n'`.
#' On top of the frame it's then possible to add a `grid`,
#' `abline` or text before plotting the lines (see: `sirspline`).
#' @export
#' @return
#' Always returns `NULL` invisibly.
#' This function is called for its side effects.
#' @family sir functions
plot.sirspline <- function(x, conf.int=TRUE, abline = TRUE, log = FALSE, type, ylab, xlab, ...) {
#print(list(...))
## premilinary checks
if (is.null(x$spline.seq.A)) stop('No splines found.')
## prepare dimension and par
plotdim <- as.numeric(c( !is.null( x$spline.seq.A ),
!is.null( x$spline.seq.B ),
!is.null( x$spline.seq.C ) ))
if(sum(plotdim) > 1) {
old_mfrow <- par("mfrow")
on.exit(par(mfrow = old_mfrow))
new_mfrow <- c(1,sum(plotdim))
par(mfrow = new_mfrow)
type <- 'l'
}
## set labels
if ( missing(xlab) ) {
xlab <- x$spline
}
if ( missing(ylab) ) {
ylab <- rep('SIR',sum(plotdim))
if(log){
ylab <- rep('log(SIR)', sum(plotdim))
}
if(x$spline.dependent & sum(plotdim) > 1) {
ylab <- c(ylab[1], paste(ylab[2:sum(plotdim)], 'ratio'))
}
}
else{
if( length(ylab) < sum(plotdim))
ylab <- rep(ylab, sum(plotdim))
if(length(ylab) > sum(plotdim)) {
warning('set ylabs in a vector length of num of plots (',sum(plotdim),')')
}
}
## set scale
if(!is.logical(log)) stop('log should be a logical value.')
log.bin <- ifelse(log, 'y', '')
## remove infinite values
#rm_inf <- function(est){
# x[[est]][ is.finite(x[[est]][[2]]) & is.finite(x[[est]][[3]]) & is.finite(x[[est]][[4]]), ]
#}
spl <- c('spline.seq.A', 'spline.seq.B', 'spline.seq.C')[1:sum(plotdim)]
est <- gsub("seq", "est", spl)
for (i in 1:sum(plotdim)) { # age, per, fot,
# empty plot
max_x <- range(x[[spl[i]]])
max_y <- range( x[[est[i]]][, 2:4] )
plot(max_x, max_y, type = 'n', ylab = ylab[i], xlab = xlab[i], log = log.bin, ...)
if(abline) abline(h = 1)
# plot lines
if (missing(type) || type != 'n') {
lines.sirspline(x, conf.int = conf.int, select.spline = i, ...)
}
}
return(invisible(NULL))
}
#' @title lines method for sirspline-object
#' @description Plot SIR spline lines with R base graphics
#'
#'
#' @author Matti Rantanen
#'
#' @param x an object returned by function sirspline
#' @param conf.int logical; default TRUE draws also the 95 confidence intervals
#' @param print.levels name(s) to be plotted. Default plots all levels.
#' @param select.spline select which spline variable (a number or a name) is plotted.
#' @param ... arguments passed on to lines()
#'
#' @details In `lines.sirspline` most of graphical parameters is user
#' adjustable.
#' Desired spline variable can be selected with `select.spline` and only one
#' can be plotted at a time. The spline variable can include
#' several levels, e.g. gender (these are the levels of `print`
#' from `sirspline`). All levels are printed by default, but a
#' specific level can be selected using argument
#' `print.levels`. Printing the levels separately enables e.g. to
#' give different colours for each level.
#'
#' @family sir functions
#'
#' @import graphics
#' @export
#' @return
#' Always returns `NULL` invisibly.
#' This function is called for its side effects.
lines.sirspline <- function(x, conf.int = TRUE, print.levels = NA, select.spline, ... ){
## input: sirspline object, with only one spline var (spline.est.A)
## input: print levels can be > 1.
## subset splines
if( length(x$spline) > 1 ) {
if ( missing(select.spline) ) {
stop(paste('select what spline to plot in select.spline:', paste(x$spline, collapse = ', ')))
}
else {
if(is.numeric(select.spline)) {
k <- select.spline
}
else {
k <- which(x$spline == select.spline)
}
if(length(k) == 0 | length(x$spline) < k) stop('select.spline name/number is incorrect')
}
}
else {
k <- 1
}
spl <- c('spline.seq.A', 'spline.seq.B', 'spline.seq.C')[k]
est <- gsub("seq", "est", spl)
## remove infinite values
# x[[h]] <- rm_inf(est=h)
# get print levels
if(missing(print.levels)) {
print.levels <- NA
}
pl <- unique(x$spline.est.A[,1])
if(any( is.null(print.levels), is.na(print.levels))) {
print.levels <- pl
}
pl <- pl[ pl %in% print.levels]
## get conf.int
if( !is.logical(conf.int) ) stop('conf.int is not logical')
n <- c(2,4)[c(!conf.int, conf.int)]
## draw lines
for( l in pl ){
# loop through print.levels
index <- which(x$spline.est.A$i == l)
for(m in 2:n) {
# loop through estiamte and confidence intervals
lines(x = x[[spl]], y = x[[est]][index, m], ...)
}
}
return(invisible(NULL))
}
#' @title Print an rate object
#' @author Matti Rantanen
#' @description Print method function for `rate` objects; see
#' `[rate]`.
#' @param x an `rate` object
#' @param subset a logical condition to subset results table by
#' before printing; use this to limit to a certain stratum. E.g.
#' `subset = sex == "female"`
#' @param ... arguments for data.tables print method, e.g. row.names = FALSE suppresses row numbers.
#' @export
#' @return
#' Always returns `NULL` invisibly.
#' This function is called for its side effects.
print.rate <- function(x, subset = NULL, ...) {
ra <- attributes(x)$rate.meta
PF <- parent.frame(1L)
TF <- environment()
subset <- evalLogicalSubset(x, substitute(subset), enclos = PF)
x <- x[subset, ]
# pre texts:
cat('\n')
if(!is.null(ra$adjust)){
if(is.character(ra$weights)) {
a <- paste(ra$weights, collapse = ',')
}
if(all(is.numeric(ra$weights))) {
a <- length(ra$weights)
}
if(is.list(ra$weights)) {
a <- sapply(ra$weights, length)
}
b <- paste(ra$adjust,a, collapse = ', ', sep = '; ')
cat('Adjusted rates (', b,') ', sep = '')
}
else{
cat('Crude rates ')
}
cat('and', '95%', 'confidence intervals:', fill=TRUE)
cat('\n')
# table itself
setDT(x)
print(x, ...)
return(invisible(NULL))
}
#' @title plot method for rate object
#' @description Plot rate estimates with confidence intervals lines using R base graphics
#' @author Matti Rantanen
#'
#' @param x a rate object (see `[rate]`)
#' @param conf.int logical; default TRUE draws the confidence intervals
#' @param eps is the height of the ending of the error bars
#' @param left.margin set a custom left margin for long variable names. Function
#' tries to do it by default.
#' @param xlim change the x-axis location
#' @param ... arguments passed on to graphical functions points and segment
#' (e.g. `col`, `lwd`, `pch` and `cex`)
#'
#' @details This is limited explanatory tool but most graphical
#' parameters are user adjustable.
#'
#' @import graphics
#' @export
#' @return
#' Always returns `NULL` invisibly.
#' This function is called for its side effects.
plot.rate <- function(x, conf.int = TRUE, eps = 0.2, left.margin, xlim, ...) {
ra <- attributes(x)$rate.meta
varcol <- ra$print
if(is.null(varcol)) {
lvl.name <- 'Crude'
}
else {
pp <- paste0('paste(', paste(varcol, collapse=','),',sep = ":")')
q <- parse(text=pp)
lvl.name <- x[,eval(q)]
}
lvls <- 1:length(lvl.name)
# WHICH RATE:
if('rate.adj' %in% names(x)) {
r <- x$rate.adj
hi <- x$rate.adj.hi
lo <- x$rate.adj.lo
}
else {
r <- x$rate
hi <- x$rate.hi
lo <- x$rate.lo
}
# X-AXIS LIMITs
if(missing(xlim)) {
t <- range(na.omit(c(lo , r, hi)))
t0 <- (t[2]-t[1])/4
xlimit <- c(pmax(t[1]-t0, 0), t[2] + t0)
}
else {
xlimit <- xlim
}
# MARGINS
old_mar <- par("mar")
on.exit(par(mar = old_mar))
if(missing(left.margin)) {
new.margin <- par("mar")
new.margin[2] <- 4.1 + sqrt( max(nchar(as.character(lvl.name))) )*2
}
else {
new.margin[2] <- left.margin
}
par(mar = new.margin)
plot(c(xlimit), c(min(lvls)-0.5, max(lvls)+0.5), type='n', yaxt = 'n', ylab = '', xlab='')
axis(side = 2, at = lvls, labels = lvl.name, las = 1)
points(r, lvls, ...)
if(conf.int) {
segments(lo, lvls, hi, lvls, ...)
segments(lo, lvls - eps, lo, lvls + eps, ...)
segments(hi, lvls - eps, hi, lvls + eps, ...)
}
return(invisible(NULL))
}
#' @export
print.yrs <- function(x, ...) {
print(as.numeric(x))
}
#' @export
`[.yrs` <- function(x, ...) {
yl <- attr(x, "year.length")
structure(NextMethod(), year.length = yl, class = c("yrs", "numeric"))
}
#' @export
`[.aggre` <- function(x, ...) {
xa <- attributes(x)
y <- NextMethod()
if (is.data.frame(y)) {
setattr(y, "class", xa$class)
setattr(y, "aggre.meta", xa$aggre.meta)
setattr(y, "breaks", xa$breaks)
}
y
}
#' @export
subset.aggre <- function(x, ...) {
y <- NextMethod()
if (is.data.frame(y)) {
setattr(y, "class", class(x))
setattr(y, "aggre.meta", attr(x, "aggre.meta"))
setattr(y, "breaks", attr(x, "breaks"))
}
y
}
preface_survtab.print <- function(x) {
surv.int <- NULL ## APPEASE R CMD CHECK
at <- attributes(x)$survtab.meta
arg <- at$arguments
cat("\n")
cat("Call: \n", oneWhitespace(deparse(at$call)), "\n")
cat("\n")
cat("Type arguments: \n surv.type:", as.character(arg$surv.type),
"--- surv.method:", as.character(arg$surv.method))
if (as.character(arg$surv.type) == "surv.rel")
cat(" --- relsurv.method:", as.character(arg$relsurv.method))
cat("\n \n")
cat("Confidence interval arguments: \n level:",
as.character(arg$conf.level*100), "%")
cat(" --- transformation:",
as.character(arg$conf.type))
cat("\n \n")
cat("Totals:")
totCat <- paste0("\n person-time:", round(sum(x$pyrs)))
if (arg$surv.method == "lifetable") {
totCat <- paste0("\n at-risk at T=0: ", round(sum(x[surv.int == 1L]$n)))
}
cat(totCat)
cat(" --- events:", sum(x$d))
cat("\n \n")
if (length(at$print.vars) > 0L) {
cat("Stratified by:", paste0("'", at$print.vars, "'", collapse = ", "))
if (length(at$adjust.vars) > 0L) cat(" --- ")
}
if (length(at$adjust.vars) > 0L) {
cat("Adjusted by:", paste0("'", at$adjust.vars, "'", collapse = ", "))
}
cat("\n")
invisible()
}
#' @title Print an `aggre` Object
#' @author Joonas Miettinen
#' @description Print method function for `aggre` objects; see
#' `[as.aggre]` and `[aggre]`.
#' @param x an `aggre` object
#' @param subset a logical condition to subset results table by
#' before printing; use this to limit to a certain stratum. E.g.
#' `subset = sex == "male"`
#' @param ... arguments passed to `print.data.table`; try e.g.
#' `top = 2` for numbers of rows in head and tail printed
#' if the table is large,
#' `nrow = 100` for number of rows to print, etc.
#' @export
#' @return
#' Always returns `NULL` invisibly.
#' This function is called for its side effects.
print.aggre <- function(x, subset = NULL, ...) {
PF <- parent.frame(1L)
TF <- environment()
sa <- attributes(x)$aggre.meta
subset <- evalLogicalSubset(x, substitute(subset), enclos = PF)
x <- x[subset, ]
setDT(x)
print(x, ...)
return(invisible(NULL))
}
#' @title Summarize an `aggre` Object
#' @author Joonas Miettinen
#' @description `summary` method function for `aggre` objects; see
#' `[as.aggre]` and `[aggre]`.
#' @param object an `aggre` object
#' @param by list of columns to summarize by - e.g. `list(V1, V2)`
#' where `V1` and `V2` are columns in the data.
#' @param subset a logical condition to subset results table by
#' before summarizing; use this to limit to a certain stratum. E.g.
#' `subset = sex == "male"`
#' @param ... unused
#' @export
#' @family aggregation functions
#' @return
#' Returns a `data.table` --- a further aggregated version of `object`.
summary.aggre <- function(object, by = NULL, subset = NULL, ...) {
PF <- parent.frame(1L)
TF <- environment()
x <- object
sa <- attributes(x)$aggre.meta
subset <- evalLogicalSubset(x, substitute(subset), enclos = PF)
x <- x[subset, ]
setDT(x)
bys <- substitute(by)
bye <- evalPopArg(x, bys, enclos = environment(), types = c("list", "NULL"))
vals <- sa$values
vals <- intersect(names(x), vals)
if (!length(vals)) {
cat("No originally created value columns appear to be left in data.")
}
r <- x[, lapply(.SD, sum), by = eval(bye), .SDcols = vals]
r
}
#' @title Print a survtab Object
#' @author Joonas Miettinen
#' @description Print method function for `survtab` objects; see
#' `[survtab_ag]`.
#' @param x a `survtab` object
#' @param subset a logical condition to subset results table by
#' before printing; use this to limit to a certain stratum. E.g.
#' `subset = sex == "male"`
#' @param ... arguments passed to `print.data.table`; try e.g.
#' `top = 2` for numbers of rows in head and tail printed
#' if the table is large,
#' `nrow = 100` for number of rows to print, etc.
#' @export
#' @family survtab functions
#' @return
#' Always returns `NULL` invisibly.
#' This function is called for its side effects.
print.survtab <- function(x, subset = NULL, ...) {
Tstart <- Tstop <- NULL ## APPEASE R CMD CHECK
PF <- parent.frame(1L)
TF <- environment()
sa <- attributes(x)$survtab.meta
subset <- evalLogicalSubset(x, substitute(subset), enclos = PF)
x <- x[subset, ]
preface_survtab.print(x)
setDT(x)
if (nrow(x) == 0L) {
print(x)
return(invisible())
}
pv <- as.character(sa$print.vars)
if (length(pv) == 0L) pv <- NULL
magicMedian <- function(x) {
if (length(x) %% 2L == 0L) median(x[-1L], na.rm = TRUE) else
median(x, na.rm = TRUE)
}
## to avoid e.g. 'factor(V1, 1:2)' going bonkers
pv_orig <- pv
if (length(pv) > 0L) {
pv <- makeTempVarName(x, pre = paste0("print_", 1:length(pv)))
setnames(x, pv_orig, pv)
}
medmax <- x[, list(Tstop = c(magicMedian(c(min(Tstart),Tstop)), max(Tstop))), keyby = eval(pv)]
setkeyv(medmax, c(pv, "Tstop"))
setkeyv(x, c(pv, "Tstop"))
x <- x[medmax]
rv <- intersect(names(x), c(sa$est.vars, sa$CI.vars, sa$misc.vars))
if (length(rv)) {
x[, (rv) := lapply(.SD, round, digits = 4L), .SDcols = rv]
}
sv <- intersect(names(x), sa$SE.vars)
if (length(sv > 0L)) {
x[, c(sv) := lapply(.SD, signif, digits = 4L), .SDcols = sv]
}
setcolsnull(x, keep = c(pv, "Tstop", sa$surv.vars), colorder = TRUE)
if (length(pv)) setnames(x, pv, pv_orig)
print(data.table(x), ...)
return(invisible(NULL))
}
#' @title Summarize a survtab Object
#' @author Joonas Miettinen
#' @description Summary method function for `survtab` objects; see
#' `[survtab_ag]`. Returns estimates at given time points
#' or all time points if `t` and `q` are both `NULL`.
#' @param object a `survtab` object
#' @param t a vector of times at which time points (actually intervals that
#' contain t) to print summary table of survival function estimates by strata;
#' values not existing in any interval cause rows containing only `NAs` to
#' be returned.
#' @param q a named `list` of quantiles to include in returned data set,
#' where names must match to estimates in `object`;
#' returns intervals where the quantiles are reached first;
#' e.g. `list(surv.obs = 0.5)` finds the interval where `surv.obs`
#' is 0.45 and 0.55 at the beginning and end of the interval, respectively;
#' returns rows with `NA` values for quantiles not reached in estimates
#' (e.g. if `q = list(surv.obs = 0.5)` but lowest estimate is 0.6);
#' see Examples.
#' @param subset a logical condition to subset results table by
#' before printing; use this to limit to a certain stratum. E.g.
#' `subset = sex == "male"`
#' @param ... unused; required for congruence with other `summary` methods
#'
#' @details
#' Note that this function returns the intervals and NOT the time points
#' corresponding to quantiles / estimates corresponding to time points.
#' If you want precise estimates at time points that are not interval breaks,
#' add the time points as breaks and re-estimate the survival time function.
#' In interval-based estimation, the estimates denote e.g. probability of
#' dying *during* the interval, so time points within the intervals
#' are not usually considered at all. See e.g. Seppa, Dyba, and Hakulinen
#' (2015).
#'
#' @references
#' Seppa K., Dyba T. and Hakulinen T.: Cancer Survival,
#' Reference Module in Biomedical Sciences. Elsevier. 08-Jan-2015.
#' \doi{10.1016/B978-0-12-801238-3.02745-8}
#'
#' @examples
#'
#' library(Epi)
#'
#' ## NOTE: recommended to use factor status variable
#' x <- Lexis(entry = list(FUT = 0, AGE = dg_age, CAL = get.yrs(dg_date)),
#' exit = list(CAL = get.yrs(ex_date)),
#' data = sire[sire$dg_date < sire$ex_date, ],
#' exit.status = factor(status, levels = 0:2,
#' labels = c("alive", "canD", "othD")),
#' merge = TRUE)
#' ## pretend some are male
#' set.seed(1L)
#' x$sex <- rbinom(nrow(x), 1, 0.5)
#' ## observed survival
#' st <- survtab(Surv(time = FUT, event = lex.Xst) ~ sex, data = x,
#' surv.type = "cif.obs",
#' breaks = list(FUT = seq(0, 5, 1/12)))
#'
#' ## estimates at full years of follow-up
#' summary(st, t = 1:5)
#'
#' ## interval estimate closest to 75th percentile, i.e.
#' ## first interval where surv.obs < 0.75 at end
#' ## (just switch 0.75 to 0.5 for median survival, etc.)
#' summary(st, q = list(surv.obs = 0.75))
#' ## multiple quantiles
#' summary(st, q = list(surv.obs = c(0.75, 0.90), CIF_canD = 0.20))
#'
#' ## if you want all estimates in a new data.frame, you can also simply do
#'
#' x <- as.data.frame(st)
#' @return
#' A `data.table`: a slice from `object` based on `t`, `subset`, and `q`.
#' @export
#' @family survtab functions
summary.survtab <- function(object, t = NULL, subset = NULL, q = NULL, ...) {
PF <- parent.frame(1L)
at <- copy(attr(object, "survtab.meta"))
subr <- copy(at$surv.breaks)
if (!is.null(t) && !is.null(q)) {
stop("Only supply either t or q.")
}
sb <- substitute(subset)
subset <- evalLogicalSubset(object, sb, enclos = PF)
x <- object[subset, ]
## to avoid e.g. 'factor(V1, 1:2)' going bonkers
pv_orig <- pv <- at$print.vars
if (length(pv) > 0L) {
pv <- makeTempVarName(x, pre = paste0("print_", 1:length(pv)))
setnames(x, pv_orig, pv)
}
setDT(x)
## quantile detection --------------------------------------------------------
if (!is.null(q)) {
bn <- setdiff(names(q), at$est.vars)
if (length(bn) > 0L) {
stop("No survival time function estimates named ",
paste0("'", bn, "'", collapse = ", "),
" found in supplied survtab object. Available ",
"survival time function estimates: ",
paste0("'", at$est.vars, "'", collapse = ", "))
}
lapply(q, function(x) {
if (min(x <= 0L) || max(x >= 1L)) {
stop("Quantiles must be expressed as numbers between 0 and 1, ",
"e.g. surv.obs = 0.5.")
}
})
m <- x[, .SD[1, ], keyby = eval(pv)][, c(pv, "Tstop"), with = FALSE]
setDF(m)
rollVars <- makeTempVarName(x, pre = names(q))
x[, c(rollVars) := lapply(.SD, copy), .SDcols = names(q)]
m <- lapply(seq_along(q), function(i) {
m <- merge(m, q[[i]])
setnames(m, "y", rollVars[i])
if (length(pv)) setorderv(m, pv)
m[, c(pv, rollVars[i]), drop = FALSE]
})
names(m) <- names(q)
l <- vector("list", length(q))
names(l) <- names(q)
for (k in names(q)) {
l[[k]] <- setDT(x[m[[k]], on = names(m[[k]]), roll = 1L])
}
l <- rbindlist(l)
set(l, j = rollVars, value = NULL)
if (length(pv)) setkeyv(l, pv)
x <- l
}
## time point detection ------------------------------------------------------
if (!is.null(t)) {
tcutv <- makeTempVarName(x, pre = "cut_time_")
set(x, j = tcutv, value = cut(x$Tstop, breaks = subr, right = TRUE,
include.lowest = FALSE))
cutt <- cut(t, breaks = subr, right = TRUE, include.lowest = FALSE)
l <- list(cutt)
names(l) <- tcutv
if (length(pv)) {
pvdt <- setDF(unique(x, by = pv))[, pv, drop = FALSE]
l <- setDT(merge(pvdt, as.data.frame(l)))
setkeyv(l, pv)
}
x <- x[l, on = c(pv, tcutv)]
set(x, j = tcutv, value = NULL)
if (length(pv)) setkeyv(x, pv)
}
## final touches -------------------------------------------------------------
if (length(pv) > 0L) setnames(x, pv, pv_orig)
if (!return_DT()) setDFpe(x)
x
}
#' @export
`[.survtab` <- function(x, ...) {
y <- NextMethod()
if (is.data.frame(y)) {
setattr(y, "class", class(x))
setattr(y, "survtab.meta", attr(x, "survtab.meta"))
}
y
}
#' @export
subset.survtab <- function(x, ...) {
y <- NextMethod()
if (is.data.frame(y)) {
setattr(y, "class", class(x))
setattr(y, "survtab.meta", attr(x, "survtab.meta"))
}
y
}
#' @export
`[.survmean` <- function(x, ...) {
y <- NextMethod()
if (is.data.frame(y)) {
setattr(y, "class", class(x))
setattr(y, "survmean.mean", attr(x, "survmean.mean"))
}
y
}
#' @export
subset.survmean <- function(x, ...) {
y <- NextMethod()
if (is.data.frame(y)) {
setattr(y, "class", class(x))
setattr(y, "survmean.mean", attr(x, "survmean.mean"))
}
y
}
#' @export
`[.rate` <- function(x, ...) {
y <- NextMethod()
if (is.data.frame(y)) {
setattr(y, "class", class(x))
setattr(y, "rate.meta", attr(x, "rate.meta"))
}
y
}
#' @export
subset.rate <- function(x, ...) {
y <- NextMethod()
if (is.data.frame(y)) {
setattr(y, "class", class(x))
setattr(y, "rate.meta", attr(x, "rate.meta"))
}
y
}
prep_plot_survtab <- function(x,
y = NULL,
subset = NULL,
conf.int = TRUE,
enclos = parent.frame(1L),
...) {
## subsetting ----------------------------------------------------------------
subset <- evalLogicalSubset(data = x, substiset = substitute(subset),
enclos = environment())
attrs <- attributes(x)
if (!inherits(x, "survtab")) stop("x is not a survtab object")
if (is.null(attrs$survtab.meta)) {
stop("Missing meta information (attributes) in survtab object; ",
"have you tampered with it after estimation?")
}
strata.vars <- attrs$survtab.meta$print.vars
x <- copy(x)
setDT(x)
x <- x[subset, ]
## detect survival variables in data -----------------------------------------
surv_vars <- c("surv.obs","CIF.rel","CIF_","r.e2","r.pp")
wh <- NULL
for (k in surv_vars) {
wh <- c(wh, which(substr(names(x), 1, nchar(k)) == k))
}
surv_vars <- names(x)[wh]
surv_vars <- surv_vars[!substr(surv_vars, nchar(surv_vars)-1, nchar(surv_vars)) %in% c("hi","lo")]
if (length(surv_vars) == 0) {
stop("x does not appear to have any survival variables; ",
"did you tamper with it after estimation?")
}
## getting y -----------------------------------------------------------------
if (!is.null(y)) {
if (!is.character(y)) {
stop("please supply y as a character string indicating ",
"the name of a variable in x")
}
if (length(y) > 1) stop("y must be of length 1 or NULL")
if (!all_names_present(x, y, stops = FALSE)) {
stop("Given survival variable in argument 'y' ",
"not present in survtab object ('", y, "')")
}
} else {
y <- surv_vars[length(surv_vars)]
if (length(surv_vars) > 1L) message("y was NULL; chose ", y, " automatically")
}
rm(surv_vars)
if (substr(y, 1, 3) == "CIF" && conf.int) {
stop("No confidence intervals currently supported for CIFs. ",
"Hopefully they will be added in a future version; ",
"meanwhile use conf.int = FALSE when plotting CIFs.")
}
## confidence intervals ------------------------------------------------------
y.lo <- y.hi <- y.ci <- NULL
if (conf.int) {
y.lo <- paste0(y, ".lo")
y.hi <- paste0(y, ".hi")
y.ci <- c(y.lo, y.hi)
badCIvars <- setdiff(y.ci, names(x))
if (sum(length(badCIvars))) {
stop("conf.int = TRUE, but missing confidence interval ",
"variables in data for y = '", y, "' (could not detect ",
"variables named", paste0("'", badCIvars, "'", collapse = ", ") ,")")
}
}
list(x = x, y = y, y.ci = y.ci, y.lo = y.lo, y.hi = y.hi,
strata = strata.vars, attrs = attrs)
}
#' `plot` method for survtab objects
#'
#' Plotting for `survtab` objects
#'
#' @import graphics
#'
#' @author Joonas Miettinen
#'
#' @param x a `survtab` output object
#' @param y survival a character vector of a variable names to plot;
#' e.g. `y = "r.e2"`
#' @param subset a logical condition; `obj` is subset accordingly
#' before plotting; use this for limiting to specific strata,
#' e.g. `subset = sex == "male"`
#' @param conf.int logical; if `TRUE`, also plots any confidence intervals
#' present in `obj` for variables in `y`
#' @param col line colour; one value for each stratum; will be recycled
#' @param lty line type; one value for each stratum; will be recycled
#' @param ylab label for Y-axis
#' @param xlab label for X-axis
#' @param ... additional arguments passed on to `plot` and
#' `lines.survtab`; e.g. `ylim` can be defined this way
#' @examples
#' data(sire)
#' data(sibr)
#' si <- rbind(sire, sibr)
#' si$period <- cut(si$dg_date, as.Date(c("1993-01-01", "2004-01-01", "2013-01-01")), right = FALSE)
#' si$cancer <- c(rep("rectal", nrow(sire)), rep("breast", nrow(sibr)))
#' x <- lexpand(si, birth = bi_date, entry = dg_date, exit = ex_date,
#' status = status %in% 1:2,
#' fot = 0:5, aggre = list(cancer, period, fot))
#' st <- survtab_ag(fot ~ cancer + period, data = x,
#' surv.method = "lifetable", surv.type = "surv.obs")
#'
#' plot(st, "surv.obs", subset = cancer == "breast", ylim = c(0.5, 1), col = "blue")
#' lines(st, "surv.obs", subset = cancer == "rectal", col = "red")
#'
#' ## or
#' plot(st, "surv.obs", col = c(2,2,4,4), lty = c(1, 2, 1, 2))
#' @export
#' @family survtab functions
#' @return
#' Always returns `NULL` invisibly.
#' This function is called for its side effects.
plot.survtab <- function(x, y = NULL, subset=NULL, conf.int=TRUE, col=NULL,lty=NULL, ylab = NULL, xlab = NULL, ...) {
Tstop <- delta <- NULL ## APPEASE R CMD CHECK
## prep ----------------------------------------------------------------------
PF <- parent.frame(1L)
subset <- substitute(subset)
subset <- evalLogicalSubset(data = x, subset, enclos = PF)
l <- prep_plot_survtab(x = x, y = y, subset = subset,
conf.int = conf.int, enclos = PF)
x <- l$x
y <- l$y
y.ci <- l$y.ci
y.lo <- l$y.lo
y.hi <- l$y.hi
## figure out limits, etc. to pass to plot() ---------------------------------
min_y <- do.call("min", c(mget(c(y, y.lo), as.environment(x)), na.rm = TRUE))
min_y <- max(min_y, 0)
max_y <- max(x[[y]], na.rm=TRUE)
if (substr(y, 1, 3) == "CIF") {
min_y <- 0.0
} else {
max_y <- max(1.0, max_y)
}
max_x <- max(x[, Tstop])
min_x <- min(x[, Tstop-delta])
if (is.null(ylab)) {
ylab <- "Observed survival"
if (substr(y[1], 1,4) %in% c("r.e2", "r.pp")) ylab <- "Net survival"
if (substr(y[1], 1,4) == "CIF_") ylab <- "Absolute risk"
if (substr(y[1], 1,6) == "CIF.rel") ylab <- "Absolute risk"
}
if (is.null(xlab)) xlab <- "Time from entry"
## attributes insurance to pass to lines.survtab
setattr(x, "survtab.meta", l$attrs$survtab.meta)
setattr(x, "class", c("survtab", "data.table", "data.frame"))
## plotting ------------------------------------------------------------------
plot(I(c(min_y,max_y))~I(c(min_x,max_x)), data=x, type="n",
xlab = xlab, ylab = ylab, ...)
lines.survtab(x, subset = NULL, y = y, conf.int=conf.int,
col=col, lty=lty, ...)
return(invisible(NULL))
}
#' `lines` method for survtab objects
#'
#' Plot `lines` from a `survtab` object
#'
#' @import graphics
#'
#' @author Joonas Miettinen
#'
#' @param x a `survtab` output object
#' @param y a variable to plot; a quoted name of a variable
#' in `x`; e.g. `y = "surv.obs"`;
#' if `NULL`, picks last survival variable column in order in `x`
#' @param subset a logical condition; `obj` is subset accordingly
#' before plotting; use this for limiting to specific strata,
#' e.g. `subset = sex == "male"`
#' @param conf.int logical; if `TRUE`, also plots any confidence intervals
#' present in `obj` for variables in `y`
#' @param col line colour passed to `matlines`
#' @param lty line type passed to `matlines`
#' @param ... additional arguments passed on to to a `matlines` call;
#' e.g. `lwd` can be defined this way
#' @examples
#' data(sire)
#' data(sibr)
#' si <- rbind(sire, sibr)
#' si$period <- cut(si$dg_date, as.Date(c("1993-01-01", "2004-01-01", "2013-01-01")), right = FALSE)
#' si$cancer <- c(rep("rectal", nrow(sire)), rep("breast", nrow(sibr)))
#' x <- lexpand(si, birth = bi_date, entry = dg_date, exit = ex_date,
#' status = status %in% 1:2,
#' fot = 0:5, aggre = list(cancer, period, fot))
#' st <- survtab_ag(fot ~ cancer + period, data = x,
#' surv.method = "lifetable", surv.type = "surv.obs")
#'
#' plot(st, "surv.obs", subset = cancer == "breast", ylim = c(0.5, 1), col = "blue")
#' lines(st, "surv.obs", subset = cancer == "rectal", col = "red")
#'
#' ## or
#' plot(st, "surv.obs", col = c(2,2,4,4), lty = c(1, 2, 1, 2))
#' @export
#' @family survtab functions
#' @return
#' Always returns `NULL` invisibly.
#' This function is called for its side effects.
lines.survtab <- function(x, y = NULL, subset = NULL,
conf.int = TRUE, col=NULL, lty=NULL, ...) {
Tstop <- NULL ## APPEASE R CMD CHECK
## prep ----------------------------------------------------------------------
PF <- parent.frame(1L)
global_breaks <- attr(x, "survtab.meta")$surv.breaks
subset <- substitute(subset)
subset <- evalLogicalSubset(data = x, subset, enclos = PF)
l <- prep_plot_survtab(x = x, y = y, subset = subset,
conf.int = conf.int, enclos = environment())
x <- l$x
y <- l$y
y.ci <- l$y.ci
y.lo <- l$y.lo
y.hi <- l$y.hi
strata <- l$strata ## character vector of var names
## impute first values (time = 0, surv = 1 / cif = 0) ------------------------
is_CIF <- if (substr(y, 1, 3) == "CIF") TRUE else FALSE
setkeyv(x, c(strata, "Tstop"))
first <- x[1, ]
if (length(strata)) first <- unique(x, by = strata)
first[, c(y) := ifelse(is_CIF, 0, 1)]
first$Tstop <- min(global_breaks)
if (length(y.ci) > 0) first[, (y.ci) := get(y) ]
x <- rbindlist(list(first, x[, ]), use.names = TRUE)
setkeyv(x, c(strata, "Tstop"))
## plotting ------------------------------------------------------------------
if (is.null(lty)) {
lty <- list(c(1,2,2))
if (!length(y.ci)) lty <- list(1)
}
lines_by(x = "Tstop", y = c(y, y.ci),
strata.vars = strata,
data = x, col = col, lty = lty, ...)
return(invisible(NULL))
}
lines_by <- function(x, y, strata.vars = NULL, data, col, lty, ...) {
## INTENTION: plots lines separately by strata,
## which may have different colours / linetypes.
## @param x a variable to plot y by; a character string
## @param y a character vector of variables to plot by x;
## e.g. the estimate and confidence interval variables
## @param strata.vars a character string vector; variables
## to add lines by, which may have different colours etc for identification
## @param data a data.frame where x, y, and strata.vars are found
## @param col a vector of colors passed to lines(); if vector length 1,
## used for each level of strata. If vector length > 1,
## has to match to total number of strata. If list, must match
## to number of strata by length and contain elements of length
## length(y).
## @param see col; line type passed to lines().
## @param ... other arguments passed on to lines().
TF <- environment()
PF <- parent.frame(1L)
stopifnot(is.data.frame(data))
stopifnot(is.character(x) && length(x) == 1L)
stopifnot(is.character(y) && length(y) > 0L)
stopifnot(is.character(strata.vars) || is.null(strata.vars))
all_names_present(data, c(x,y,strata.vars))
d <- mget(c(strata.vars, y, x), envir = as.environment(data))
setDT(d)
setkeyv(d, c(strata.vars, x))
## create list of datas
l <- list(d)
inter <- 1L
if (length(strata.vars)) {
inter <- do.call(interaction, d[, strata.vars, with = FALSE])
l <- vector("list", uniqueN(inter))
l <- split(d, f = inter, drop = TRUE)
}
l <- lapply(l, function(tab) {
setDT(tab)
setcolsnull(tab, keep = c(x, y))
tab
})
## figure out colours and ltys
for (objname in c("col", "lty")) {
obj <- TF[[objname]]
if (missing(obj) || !length(obj)) obj <- 1
if (!length(obj) %in% c(1, length(l))) {
stop("Argument ", objname, " is not of length 1 or ",
"of length equal to total number of strata (",
length(l), ").")
}
ol <- unlist(lapply(obj, length))
if (length(y) > 1 && is.list(obj) && !all(ol %in% c(1, length(y)))) {
stop("Argument y is of length > 1, and you passed ",
objname, " as a list of values, but at least one element is not ",
"of length 1 or length(y).")
}
## NOTE: rep works for vector and list just the same
if (length(obj) == 1) obj <- rep(obj, length(l))
obj <- as.list(obj)
assign(x = objname, value = obj)
}
lapply(seq_along(l), function(i) {
tab <- l[[i]]
cols <- col[[i]]
ltys <- lty[[i]]
matlines(x = tab[[x]], y = tab[, y, with = FALSE],
col = cols, lty = ltys, ...)
})
invisible(NULL)
}
#' @title Graphically Inspect Curves Used in Mean Survival Computation
#' @description Plots the observed (with extrapolation) and expected survival
#' curves for all strata in an object created by `[survmean]`
#' @author Joonas Miettinen
#' @param x a `survmean` object
#' @param ... arguments passed (ultimately) to `matlines`; you
#' may, therefore, supply e.g. `xlab` through this, though arguments
#' such as `lty` and `col` will not work
#' @details
#'
#' For examples see `[survmean]`. This function is intended only
#' for graphically inspecting that the observed survival curves with extrapolation
#' and the expected survival curves have been sensibly computed in `survmean`.
#'
#' If you want finer control over the plotted curves, extract the curves from
#' the `survmean` output using
#'
#' `attr(x, "curves")`
#'
#' where `x` is a `survmean` object.
#' @export
#' @family survmean functions
#' @return
#' Always returns `NULL` invisibly.
#' This function is called for its side effects.
plot.survmean <- function(x, ...) {
at <- attr(x, "survmean.meta")
curves <- at$curves
if (is.null(curves)) {
stop("no curves information in x; sometimes lost if x ",
"altered after using survmean")
}
by.vars <- at$tprint
by.vars <- c(by.vars, at$tadjust)
by.vars <- intersect(by.vars, names(curves))
if (!length(by.vars)) by.vars <- NULL
plot(curves$surv ~ curves$Tstop, type="n",
xlab = "Time from entry", ylab = "Survival")
lines.survmean(x, ...)
subr <- at$breaks[[at$survScale]]
abline(v = max(subr), lty=2, col="grey")
if (length(by.vars)) {
## add legend denoting colors
Stratum <- curves[, unique(interaction(.SD)), .SDcols = eval(by.vars)]
legend(x = "topright", legend = Stratum, col = seq_along(Stratum), lty = 1)
}
return(invisible(NULL))
}
#' @title Graphically Inspect Curves Used in Mean Survival Computation
#' @description Plots the observed (with extrapolation) and expected survival
#' curves for all strata in an object created by `[survmean]`
#' @author Joonas Miettinen
#' @param x a `survmean` object
#' @param ... arguments passed (ultimately) to `matlines`; you
#' may, therefore, supply e.g. `lwd` through this, though arguments
#' such as `lty` and `col` will not work
#' @details
#'
#' This function is intended to be a workhorse for `[plot.survmean]`.
#' If you want finer control over the plotted curves, extract the curves from
#' the `survmean` output using
#'
#' `attr(x, "curves")`
#'
#' where `x` is a `survmean` object.
#' @export
#' @family survmean functions
#' @return
#' Always returns `NULL` invisibly.
#' This function is called for its side effects.
lines.survmean <- function(x, ...) {
at <- copy(attr(x, "survmean.meta"))
curves <- at$curves
if (is.null(curves)) stop("no curves information in x; usually lost if x altered after using survmean")
by.vars <- at$tprint
by.vars <- c(by.vars, at$tadjust)
by.vars <- c("survmean_type", by.vars)
by.vars <- intersect(by.vars, names(curves))
if (!length(by.vars)) by.vars <- NULL
curves <- data.table(curves)
setkeyv(curves, c(by.vars, "Tstop"))
type_levs <- length(levels(interaction(curves[, c(by.vars), with=FALSE])))/2L
other_levs <- 1L
if (length(by.vars) > 1) {
other_levs <- length(levels(interaction(curves[, setdiff(by.vars, "survmean_type"), with=FALSE])))
}
curves <- cast_simple(curves, columns = by.vars, rows = "Tstop", values = "surv")
matlines(x=curves$Tstop, y=curves[, setdiff(names(curves), "Tstop"), with=FALSE],
lty = rep(1:2, each=type_levs), col = 1:other_levs, ...)
return(invisible(NULL))
}
#' @export
getCall.survtab <- function(x, ...) {
attributes(x)$survtab.meta$call
}
#' @export
formula.survtab <- function(x, ...) {
attr(x, "survtab.meta")$arguments$formula
}
#' @export
getCall.survmean <- function(x, ...) {
attributes(x)$survmean.meta$call
}
#' @export
formula.survmean <- function(x, ...) {
attr(x, "survmean.meta")$formula
}
|