我经常使用 R 包 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)
to:
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() 这里存在一些问题,但我无法弄清楚它是什么或如何修复它。
有人可以帮忙吗?