我在R package utils中经常使用head(d)和tail(d)方法 - 经常一个接一个地使用。所以我为这两个函数编写了一个简单的包装器:
ht <- function(d, m=5, n=m){
# print the head and tail together
cat(" head --> ", head(d,m), "\n", "--------", "\n", "tail --> ", tail(d,n), "\n")
}
我得到了一些意想不到的结果......有人可以帮我理解为什么吗? (所以我可以解决它......或者至少了解你的解决方案!)。
一些背景......
数字很好:
x <- 1:100
ht(x)
复杂:
ni <- as.complex(1:100)
ht(ni)
和字符:
ll <- letters[1:26]
ht(ll)
矩阵失去了它的结构,将[1,1]返回到[5,5] + [16,1]到[20,5]但是作为两个向量 - 比较:
m <- matrix(1:10, 20)
ht(m)
为:
head(m, 5)
tail(m,5)
我想保留矩阵结构,就像utils方法那样 - 这可能吗?
最后(好吧,可能会有更多的错误,这就是我要做的事情)data.frames是一团糟:
df <- data.frame(num=x[1:26], char=ll)
ht(df)
这会产生以下错误:
head --> Error in cat(list(...), file, sep, fill, labels, append) :
argument 2 (type 'list') cannot be handled by 'cat'
到目前为止的步骤:
由于utils方法在按位完成时保持矩阵整洁,我尝试通过以下编辑来解决问题:
function(d, m=5, n=m){
# print the head and tail together
rb <- rbind(head(d, m), tail(d,n))
if (class(d) == 'matrix'){
len <- nrow(rb)
cat(" head --> ", rb[(1:m),], "\n", "--------", "\n", "tail --> ", rb[((len-n):len),], "\n")
}
else cat(" head --> ", rb[1,], "\n", "--------", "\n", "tail --> ", rb[2,], "\n")
}
对于矩阵似乎没有做任何事情......当我
时仍然会出现相同的错误ht(df)
我猜错了cat()这里有一些问题,但我无法弄清楚它是什么或如何修复它。
有人可以帮忙吗?
答案 0 :(得分:7)
为什么不修改你的功能来输出一个列表呢?
ht <- function(d, m=5, n=m){
# print the head and tail together
list(HEAD = head(d,m), TAIL = tail(d,n))
}
以下是matrix
和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
答案 1 :(得分:4)
有人建议我将评论转为答案。
在您的R控制台中,当您键入head(m, 5)
时,您在屏幕上看到的内容实际上是print(head(m, 5))
的结果。因此,如果这是您希望输出显示的内容,请在显示对象的print
和cat
时考虑使用head
函数而不是tail
:
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
我发现@mrdwab的答案是一个非常优雅的解决方案。它没有明确使用print
,而是返回一个列表。但是,当从R控制台调用其函数并且未将输出分配给任何内容时,它将被打印到控制台(因此隐式使用print
)。我希望这可以帮助你了解正在发生的事情。
答案 2 :(得分:0)
如果您已经在使用tidyverse
原理进行编码并且使用了%>%
(管道)运算符,那么实际上只有一条线很容易:
library(magrittr)
your_dataframe %>% {
rbind(head(., 8), tail(., 8)
} %>%
nrow()
# [1] 16
这基本上是使用rbind
来合并head()
的顶部tail()
和底部your_dataframe
。 {}
用于调用lambda表达式(更多信息here)。 .
和head
中的tail
表示“标准输入”(your_dataframe
)。