0

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.

3
  • It still doesn't work. It doesn't even work for one plot. Commented Nov 21, 2018 at 10:04
  • 2
    Sorry to hear that, if you won't make a reproducible example it is hard to test our suggestions. Commented Nov 21, 2018 at 10:05
  • Why get? Try for (i in 1:5) plotLibrarySize(t[i], 2500) Commented Nov 21, 2018 at 10:15

1 Answer 1

2

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Very informative, very helpful and so many examples. thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.