same value returned by lm_eqn function in loop

27 views
Skip to first unread message

jhzhao1

unread,
Nov 16, 2014, 7:02:56 PM11/16/14
to ggp...@googlegroups.com
Hi,

I want to add equation to each plot I made when I was doing a serial of plots. But I have problem when loop the function lm_eqn(). All the equation gets the  the value of my last sample. 
Could anyone help me with this?

Thank you very much!

The code is below:

for(i in 3:5) {
sample <- SNPdata[,i]
ref <- SNPdata$Ref
df <- cbind(ref, sample)
df <- data.frame(df)

lm_eqn <- function(df) {
  mat = lm(ref~sample, df);
  eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2, 
                   list(a = format(coef(mat)[1], digits = 2), 
                        b = format(coef(mat)[2], digits = 2), 
                        r2 = format(summary(mat)$r.squared, digits = 3)))
  as.character(as.expression(eq)); 

}

lm_eqn(df)

print(eq)


}

Brian Diggs

unread,
Nov 17, 2014, 12:13:09 PM11/17/14
to jhzhao1, ggplot2
On 11/16/14 4:02 PM, jhzhao1 wrote:
> Hi,
>
> I want to add equation to each plot I made when I was doing a serial of
> plots. But I have problem when loop the function lm_eqn(). All the equation
> gets the the value of my last sample.
> Could anyone help me with this?

This is a good improvement over your previous question and you have
narrowed the problem down. At this point, you have actually removed all
ggplot from the question and shown that is not the problem (and so, this
isn't really the right list anymore).

However, we don't have SNPdata, so it is still not reproducible as-is. I
made a mock version that I could use with your example.

SNPdata <- mtcars
colnames(SNPdata)[1] <- "Ref"

> Thank you very much!
>
> The code is below:
>
> for(i in 3:5) {
> sample <- SNPdata[,i]
> ref <- SNPdata$Ref
> df <- cbind(ref, sample)
> df <- data.frame(df)
>
> lm_eqn <- function(df) {
> mat = lm(ref~sample, df);
> eq <- substitute(italic(y) == a + b %.%
> italic(x)*","~~italic(r)^2~"="~r2,
> list(a = format(coef(mat)[1], digits = 2),
> b = format(coef(mat)[2], digits = 2),
> r2 = format(summary(mat)$r.squared, digits = 3)))
> as.character(as.expression(eq));
>
> }
>
> lm_eqn(df)
>
> print(eq)
>
>
> }
>

There is no eq defined inside your loop. There is one inside lm_eqn, but
that is not available when you call print(eq). So any eq that is printed
is from your global environment and is probably something lying around
from testing the code and is therefore static. If I change the last two
lines inside the loop to print(lm_eqn(df)), I get a different value for
each iteration.

--
Brian Diggs
Reply all
Reply to author
Forward
0 new messages