简体   繁体   中英

How do I create a print function in R?

The following is my data,

Number Score
0.00 4.00
0.31 2.07
0.63 2.15
0.94 3.08
1.26 4.09
1.57 2.39
1.88 1.96
2.20 3.72

I want to create a function that on output gives me,

Scores by Number (z = 8)

Number Score
0.00 4.00
0.31 2.07
0.63 2.15
0.94 3.08
1.26 4.09

5 more rows

I know that the skeleton of the function should look something like this, but I've never dealt with also providing words/phrases on output.

print <- function(x, ...)
{

}

We can use paste , cat , print to print the output

print_new <- function(dat) {
      nr <- nrow(dat)
      n <- 5
      n1 <- nr - n
      cat(sprintf("Scores by Number (z = %d)", nr), "\n")
      cat('', '\n')
      print(head(dat, n))
      cat('', '\n')
      cat(sprintf('%d more rows', n1))




  }

print_new(df1)
#Scores by Number (z = 8) 

#  Number Score
#1   0.00  4.00
#2   0.31  2.07
#3   0.63  2.15
#4   0.94  3.08
#5   1.26  4.09

#3 more rows

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM