如何使用Rmarkdown/Knitr从同一代码行返回紧凑的head()和tail()结果?

如何使用Rmarkdown/Knitr从同一代码行返回紧凑的head()和tail()结果?,r,concatenation,knitr,head,r-markdown,R,Concatenation,Knitr,Head,R Markdown,目标:我想使用Rmarkdown/Knitr中的一行代码返回相邻或至少紧凑的head和tail结果 我意识到我可以在同一代码行上使用c实现某些功能,并在同一结果行上打印,例如,cmeanvector,sdvector将返回[1]20.663 6.606 但是,如果我尝试使用cheaddata、taildata,我会得到一个列表,而不是矩阵/df,如果我使用headdata;taildata结果将在R控制台中连续显示上/下,但在Rmarkdown/Knitr中仅返回taildata结果 复制步骤:

目标:我想使用Rmarkdown/Knitr中的一行代码返回相邻或至少紧凑的head和tail结果

我意识到我可以在同一代码行上使用c实现某些功能,并在同一结果行上打印,例如,cmeanvector,sdvector将返回[1]20.663 6.606

但是,如果我尝试使用cheaddata、taildata,我会得到一个列表,而不是矩阵/df,如果我使用headdata;taildata结果将在R控制台中连续显示上/下,但在Rmarkdown/Knitr中仅返回taildata结果

复制步骤:

使用以下R区块创建Rmd文件:

```{r Load Data, cache=TRUE,echo=TRUE}

require("datasets") ## ensure User has the R datasets package installed
data("ToothGrowth") ## load the ToothGrowth dataset
head(ToothGrowth, n = 2); tail(ToothGrowth, n = 2) ## attempt compact results

```
按Ctrl+shift+k组合键编织Rmd或选择编织HTML动作

相关结果:

供参考设置:


试试这个

cbind(head(ToothGrowth, n = 2), tail(ToothGrowth, n = 2))

   len supp dose  len supp dose
1  4.2   VC  0.5 29.4   OJ    2
2 11.5   VC  0.5 23.0   OJ    2

knitr似乎有一个bug,它是从evaluate包继承来的,并且不会从同一行中用分号分隔的表达式生成两个打印结果

你可能会得到你想要的东西

> rbind(head(ToothGrowth, 2), tail(ToothGrowth, 2))
    len supp dose
1   4.2   VC  0.5
2  11.5   VC  0.5
59 29.4   OJ  2.0
60 23.0   OJ  2.0

如果添加具有行名称的列会怎么样

library("datasets")
data("ToothGrowth")

# Add a leading column with row names
add_n_line <- function(df) {
  col_names <- colnames(df)
  df$n <- rownames(df)
  df[, c("n", col_names)]
}

print(cbind(add_n_line(head(ToothGrowth, n = 2)),
            add_n_line(tail(ToothGrowth, n = 2))),
      row.names = FALSE)

 ## n  len supp dose  n  len supp dose
 ## 1  4.2   VC  0.5 59 29.4   OJ    2
 ## 2 11.5   VC  0.5 60 23.0   OJ    2

另一个选项是来自psych包的函数headTail。我们传递参数ellipsis=FALSE,这样头部和尾部就不会被点分开

library(psych)    
headTail(ToothGrowth, top = 2, bottom = 2, ellipsis = FALSE)
输出:


尝试cbindheaddata、taildata.update.packages,正如knitr常见问题1所说:@Yihui。这似乎解决了意外行为。谢谢谢谢你的确认!谢谢你的建议。我对这个解决方案的担忧是,我不清楚最后三列是来自观察值59/60,而不是1/2。为了保持观察/行的完整性,我更喜欢rbind。但是,rbind需要多消耗2行输出。我担心再使用两行的唯一原因是我分配的空间有限。或者do.callrbind、lapplyhead、tail、do.call、listn=2、x=irisys,这正是您很久以前报告的错误,并且固定版本已经在CRAN上运行了四个月。在这种情况下,knitr FAQ 1再次适用:@Bill Venables。谢谢你的回复。在完成了Yihui建议的更新之后,看起来最好的解决方案是,我认为除非有人使用rbind发布更好的东西,因为;选项实际上给出了前两个观测值下的完整输出观测值+列标题。再次感谢。
library("datasets")
data("ToothGrowth")

# Add a leading column with row names
add_n_line <- function(df) {
  col_names <- colnames(df)
  df$n <- rownames(df)
  df[, c("n", col_names)]
}

print(cbind(add_n_line(head(ToothGrowth, n = 2)),
            add_n_line(tail(ToothGrowth, n = 2))),
      row.names = FALSE)

 ## n  len supp dose  n  len supp dose
 ## 1  4.2   VC  0.5 59 29.4   OJ    2
 ## 2 11.5   VC  0.5 60 23.0   OJ    2
library(psych)    
headTail(ToothGrowth, top = 2, bottom = 2, ellipsis = FALSE)
    len supp dose
1   4.2   VC  0.5
2  11.5   VC  0.5
59 29.4   OJ  2.0
60 23.0   OJ  2.0