首页 > 解决方案 > 我在 R 中的函数没有绘制绘图

问题描述

我有一个计算库大小并绘制直方图的函数。

函数看起来像这样

 plotLibrarySize <- function(t, cutoffPoint) {
        options(repr.plot.width=4, repr.plot.height=4)

        hist(
            t$total_counts,
            breaks = 100
        )
        abline(v = cutoffPoint, col = "red")
    }

我的环境中有一个从 t_1 到 t_n 的对象列表,我循环这些对象以获取文件的大小。

for (i in 1:length(paths))
print(sum(get(t[i])$total_counts))

现在正常绘制它我会使用

plotLibrarySize(t_1,2500)

但是,由于我有很多对象,我正在使用循环

for (i in 1:5)
plotLibrarySize(get(t[i]), 2500)

这不会产生任何图或抛出错误。有点混乱。

标签: r

解决方案


由于没有示例,因此很难看出问题。但是,下面的示例为我生成了三个图。

bar_1 <- data.frame(total_counts=rnorm(1000))
bar_2 <- data.frame(total_counts=rnorm(1000,1))
bar_3 <- data.frame(total_counts=rnorm(1000,2))

foo = function(t, cutoffPoint) {
  options(repr.plot.width=4, repr.plot.height=4)
  x=hist(t$total_counts,breaks=100)
  abline(v=cutoffPoint, col="red")
}

for(i in 1:3){
  foo(get(paste0("bar_",i))["total_counts"], 2)
}  

或者,参考您的列表(?),这也有效:

bars = list(bar_1, bar_2, bar_3)
for(i in 1:3){
  foo(get("bars")[[i]]["total_counts"], 2)
}

如前所述,使用列表get是不必要的:

bars = list(bar_1, bar_2, bar_3)
for(i in 1:3){
  foo(bars[[i]]["total_counts"], 2)
}

推荐阅读