combining head and tail methods in R

大城市里の小女人 提交于 2019-12-04 11:12:16

Why not modify your function to output a list instead?

ht <- function(d, m=5, n=m){
  # print the head and tail together
  list(HEAD = head(d,m), TAIL = tail(d,n))
}

Here's the output for your matrix and data.frame:

ht(matrix(1:10, 20))
# $HEAD
#      [,1]
# [1,]    1
# [2,]    2
# [3,]    3
# [4,]    4
# [5,]    5
# 
# $TAIL
#       [,1]
# [16,]    6
# [17,]    7
# [18,]    8
# [19,]    9
# [20,]   10

ht(data.frame(num=x[1:26], char=ll))
# $HEAD
#   num char
# 1   1    a
# 2   2    b
# 3   3    c
# 4   4    d
# 5   5    e
# 
# $TAIL
#    num char
# 22  22    v
# 23  23    w
# 24  24    x
# 25  25    y
# 26  26    z

It was suggested I turn my comment into an answer.

In your R console, when you type head(m, 5), what you see printed on your screen is really the result of print(head(m, 5)). So if this is what you want your output to look like, consider using the print function rather than cat when displaying the head and tail of your objects:

ht <- function(d, m=5, n=m) {
  # print the head and tail together
  cat("head -->\n")
  print(head(d,m))
  cat("--------\n")
  cat("tail -->\n")
  print(tail(d,n))
}

m <- matrix(1:10, 20)
ht(m)
# head -->
#      [,1]
# [1,]    1
# [2,]    2
# [3,]    3
# [4,]    4
# [5,]    5
# --------
# tail -->
#       [,1]
# [16,]    6
# [17,]    7
# [18,]    8
# [19,]    9
# [20,]   10

I find @mrdwab's answer to be a very elegant solution. It does not explicitly use print, instead returns a list. However, when his function is called from the R console and the output is not assigned to anything, then it is printed to the console (hence print is used implicitly). I hope that helps you understand what's going on.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!