Say I want to print a large object in R, such as
x <- 1:2e3
When I print x
, the R console fills the screen with its elements and, since it doesn't fit all in the screen, it will scroll down. Then I have to scroll back up to see everything that went off screen.
What I would like is to have a command that would print x
and stop when the screen fills, requiring the user to do something (like press enter) in order to have another screen full of data displayed. What I have in mind is something similar to MS DOS's dir /p
command. Is there such a thing?
As suggested by @baptiste, this solution, page(x, method = 'print')
, doesn't really solve my problem. To be more clear, what I would like is a solution that wouldn't involve printing the object in another window, as this would disrupt my workflow. If I didn't care for this, I'd just use View()
or something similar.
Here is a quick and dirty more
function:
more <- function(expr, lines=20) {
out <- capture.output(expr)
n <- length(out)
i <- 1
while( i < n ) {
j <- 0
while( j < lines && i <= n ) {
cat(out[i],"\n")
j <- j + 1
i <- i + 1
}
if(i<n) readline()
}
invisible(out)
}
It will evaluate the expression and print chunks of lines (default to 20, but you can change that). You need to press 'enter' to move on to the next chunk. Only 'Enter' will work, you can't just use the space bar or other keys like other programs and it does not have options for searching, going back, etc.
You can try it with a command like:
more( rnorm(250) )
Here is an expanded version that will quit if you type 'q' or 'Q' (or anything starting with either) then press 'Enter', it will print out the last lines
rows of the output if you type 'T' then enter, and if you type a number it will jump to that decile through the output (e.g. typing 5 will jump to half way through, 8 will be 80% of the way through). Anything else and it will continue.
more <- function(expr, lines=20) {
out <- capture.output(expr)
n <- length(out)
i <- 1
while( i < n ) {
j <- 0
while( j < lines && i <= n ) {
cat(out[i],"\n")
j <- j + 1
i <- i + 1
}
if(i<n){
rl <- readline()
if( grepl('^ *q', rl, ignore.case=TRUE) ) i <- n
if( grepl('^ *t', rl, ignore.case=TRUE) ) i <- n - lines + 1
if( grepl('^ *[0-9]', rl) ) i <- as.numeric(rl)/10*n + 1
}
}
invisible(out)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With