繁体   English   中英

使函数返回多个对象时如何删除索引括号?

[英]How to remove indexing brackets when making functions return multiple objects?

我正在尝试使用函数来减少代码行,但是我的 output 并不像我想要的那样干净。 具体来说,当从 function 返回多个元素(通过制作列表并使用return )时, R 还会打印我认为是索引号的内容(例如[[1]][[1]][[1]] )。 为了使我的 markdown 文档更清晰、更具可读性,我想删除那些小数字。

关于如何做到这一点的任何想法? 环顾四周,并没有真正把我带到任何地方。 cat() 在这里不起作用,因为我试图返回 plot 和一张桌子。

使用 iris 数据集的示例(使用 ggplot2、dplyr 和 kableExtra 包):

data(iris)

TypeLoop <- function(fun) {
  all <- fun(c("setosa","versicolor","virginica"),"All")
  set <- fun("setosa","Setosa")
  vers <- fun("versicolor","Versicolor")
  virg <- fun("virginica","Verginica")
  out <- list(all,set,vers,virg)
  return(out)
}

PlotNTable <- function(type,name) {
  myplot <- ggplot(iris,aes(Sepal.Length)) +
    geom_histogram(data=filter(iris, Species %in% type),color="white",fill="darkblue") +
    labs(x="Sepal Length", y="Frequency",
         title=paste(name,": Sepal Length"))

  sep.table <- iris %>%
    filter(Species %in% type) %>%
    group_by(Sepal.Length) %>%
    summarize("Less than 6" = sum(Sepal.Length<6),
                "6 to 7" = sum(Sepal.Length<7 & Sepal.Length>=6),
                "More than 7" = sum(Sepal.Length>7))
  mytable <- kable(sep.table, caption = paste(name,": Sepal Length")) %>%
    kable_styling(c("striped","bordered","hover")) %>%
    column_spec(1, bold = T) 

  #Make the function return both objects
  out <- list(myplot,mytable)
  return(out)
}

#Return the plots and tables
TypeLoop(PlotNTable)

我在代码块的顶部包含了results='asis'选项,以使其真正编织 markdown 文档。

另外,我对 R 还很陌生,所以如果你看到危险信号/冗余/更好的方法来做我试图在这段代码中做的事情,请告诉我!

使用您的代码,我认为这将产生您想要的效果。 使用flatten()删除列表层次结构,并使用walk()迭代并仅打印其副作用的结果。

library(purrr)

#Return the plots and tables
x <- TypeLoop(PlotNTable)

walk(flatten(x), print)

使用c代替list应该可以减轻痛苦。

TypeLoop <- function(fun) {
  all <- fun(c("setosa","versicolor","virginica"),"All")
  set <- fun("setosa","Setosa")
  vers <- fun("versicolor","Versicolor")
  virg <- fun("virginica","Verginica")
  return( c(all, set, vers, virg) )
}

rest 我不能肯定地说,因为我没有在 knitr 环境中尝试过。 但接下来我要尝试的是这样的。 它似乎在控制台中工作。 你应该可以从这里弄清楚。

output <- function(x) {
  if ("gg" %in% class(x)) { 
    print(x)
  } else if ("knitr_kable" %in% class(x)) {
    cat(unlist(x), "\n")
  }
}
sapply(TypeLoop(PlotNTable), output)

那是你要找的吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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