Angelo
Angelo

Reputation: 5059

My function in R is not plotting the plot

I have a function that counts the size of the library and plots the histograms.

The function looks like this

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

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

I have a list of objects in my environment from t_1 to t_n that I loop over to get the size of the files.

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

now to plot it normally I would be using

plotLibrarySize(t_1,2500)

However, as I have many objects I am using loop

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

This generates no plots or throws error. Bit confusing.

Upvotes: 0

Views: 828

Answers (1)

Ben
Ben

Reputation: 784

Since there is no example, it's a little hard to see the problem. However, the example below produces three plots for me.

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)
}  

Alternatively, referring to your list (?), this also works:

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

As pointed out before, with lists, get is unnecessary:

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

Upvotes: 2

Related Questions