Graham Williams has a nice document on how to format knitr output here. One thing that is missing is how to selectively show lines of R output. The syntax below should do the trick (make sure you put it in your knitr source syntax)
This is the syntax
opts_chunk$set(out.top=NULL)
opts_chunk$set(out.bot=NULL)
hook_output <- knit_hooks$get("output")
knit_hooks$set(output = function(x, options) {
if (options$results != "asis"){
x <- unlist(stringr::str_split(x, "\n"))
if (!is.null(n <- options$out.top))
{
if (length(x) > n)
{
if (is.null(m <-options$out.bot)) m <- 0
x <- c(head(x, n+1), "\n....\n", tail(x, m+2))
}
}
}
x <- paste(x, collapse="\n")
hook_output(x, options)
}
)
Test the syntax
library(BaylorEdPsych)
data(MLBPitching2011)
Regular output
table(MLBPitching2011$ERAP)
##
## 13 17 18 29 31 32 33 34 36 37 38 40 41 42 43 44 45 46
## 1 2 1 2 1 2 1 1 3 4 4 2 2 3 3 2 3 1
## 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
## 3 1 1 3 5 1 2 4 3 2 7 3 2 5 7 5 1 2
## 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
## 1 6 7 7 5 2 6 7 8 7 6 5 11 6 7 11 5 2
## 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
## 9 5 8 5 4 9 5 12 6 2 9 7 5 12 8 5 3 9
## 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
## 5 6 7 8 2 12 6 5 7 7 8 5 4 4 2 4 6 3
## 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
## 6 3 7 8 6 2 3 2 4 5 7 7 6 3 2 1 2 4
## 137 138 139 141 142 143 144 145 146 147 148 149 150 152 153 154 156 157
## 5 2 3 3 1 2 1 4 2 2 3 2 3 2 1 4 1 3
## 158 160 161 162 163 164 165 167 169 170 172 176 179 180 182 185 187 192
## 2 3 1 4 2 2 1 1 2 1 2 2 1 1 3 2 1 1
## 194 195 196 197 199 200 203 206 207 208 210 211 212 213 216 217 223 230
## 1 1 1 1 1 1 1 1 1 1 1 3 1 1 1 1 1 1
## 231 236 237 239 258 261 279 285 344 380 385 388 393 407 411 460 531
## 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1
Abbreviated output
table(MLBPitching2011$ERAP)
##
## 13 17 18 29 31 32 33 34 36 37 38 40 41 42 43 44 45 46
## 1 2 1 2 1 2 1 1 3 4 4 2 2 3 3 2 3 1
....
## 194 195 196 197 199 200 203 206 207 208 210 211 212 213 216 217 223 230
## 1 1 1 1 1 1 1 1 1 1 1 3 1 1 1 1 1 1
## 231 236 237 239 258 261 279 285 344 380 385 388 393 407 411 460 531
## 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1
print(sessionInfo(), locale = FALSE)
## R version 3.0.1 (2013-05-16)
## Platform: x86_64-apple-darwin10.8.0 (64-bit)
##
## attached base packages:
## [1] stats graphics grDevices utils datasets methods base
##
## other attached packages:
## [1] BaylorEdPsych_0.5 knitr_1.2 RWordPress_0.2-3 lavaan_0.5-13
## [5] quadprog_1.5-5 pbivnorm_0.5-1 mnormt_1.4-5 boot_1.3-9
## [9] MASS_7.3-26
##
## loaded via a namespace (and not attached):
## [1] codetools_0.2-8 digest_0.6.3 evaluate_0.4.3 formatR_0.7
## [5] markdown_0.5.4 RCurl_1.95-4.1 stats4_3.0.1 stringr_0.6.2
## [9] tools_3.0.1 XML_3.95-0.2 XMLRPC_0.3-0