How to make 'head' be applied automatically to output?
r
Solution
I'd go along with @thelatemail's suggestion, i.e. redefine `print.data.frame`:
print.data.frame <- function(df) {
if (nrow(df) > 10) {
base::print.data.frame(head(df, 5))
cat("----\n")
base::print.data.frame(tail(df, 5))
} else {
base::print.data.frame(df)
}
}
data.frame(x=1:100, y=1:100)
# x y
# 1 1 1
# 2 2 2
# 3 3 3
# 4 4 4
# 5 5 5
# ----
# x y
# 96 96 96
# 97 97 97
# 98 98 98
# 99 99 99
# 100 100 100
A more elaborate version could line everything up together and avoid the repeated header, but you get the idea.
You could put such function in your `.Rprofile` or `Rprofile.site` files (see `?Startup`) so it will be there every time you start an R session.
Problem
I have a bunch of large dataframes, so every time I want to display them, I have to use `head`: ``` head( blahblah(somedata) ) ``` Typing head all the time gets old after the first few hundred times, so I'd like an easy way to do this if possible. One of the cool things about R compared to java that things like this are often really easy, if you know the secret incantation. I searched in options, and found `max.print`, which almost works, except there is now a time delay. ``` head( blahblah(somedata) ) ``` .... is instantaneous (to within the limits of my perception) ``` options(max.print=100) blahblah(somedata) ``` .... takes about 3 seconds, so longer than typing `head` Is there some way of making `head` be applied automatically when printing large data structures? An piece of code which reproduces this behavior: ``` long_dataset = data.frame(a = runif(10e5), b = runif(10e5), c = runif(10e5)) system.time(head(long_dataset)) options(max.print = 6) system.time(print(long_dataset)) ```